Ser*_*Sob 30 soft-delete laravel eloquent laravel-4
我正在尝试实现软删除概念.
这是我的对象:
class Post extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'posts';
protected $softDelete = true;
...
Run Code Online (Sandbox Code Playgroud)
软删除已开启.
现在,如果我'删除'帖子,它会获得'deleted_at'时间戳:

问题是,当我搜索或仅用于all()显示帖子时,会在那里显示软删除的项目.怎么了?
dev*_*evo 46
有时候,你会得到soft deleted表条目,get()即使是雄辩和protected $softDelete = true;.
所以要避免这个问题,请使用
...->whereNull('deleted_at')->get();
Run Code Online (Sandbox Code Playgroud)
例如,此查询将获取包括软删除的所有行.
DB::table('pages')->select('id','title', 'slug')
->where('is_navigation','=','yes')
->where('parent_id','=',$parent_id)
->orderBy('page_order')
->get();
Run Code Online (Sandbox Code Playgroud)
所以正确的方法是,
DB::table('pages')->select('id','title', 'slug')
->where('is_navigation','=','yes')
->where('parent_id','=',$parent_id)
->whereNull('deleted_at')
->orderBy('page_order')
->get();
Run Code Online (Sandbox Code Playgroud)
Thi*_*ata 32
在laravel中使用软删除表和查询有一个小技巧:
当我们创造类似的东西
$objCars = Car::where("color","blue");
Run Code Online (Sandbox Code Playgroud)
系统执行类似的操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
"color" = 'blue'
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.但是,当我们应用"orWhere"方法时,会发生一些有趣的事情
$objCars = Car::where("color","blue")->orWhere("color","red");
Run Code Online (Sandbox Code Playgroud)
系统将执行类似的操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
"color" = 'blue'
OR
"color" = 'red'
Run Code Online (Sandbox Code Playgroud)
这个新查询将返回所有车辆,其中deleted_at为空,颜色为蓝色或者如果颜色为红色,即使deleted_at不为空.这与其他查询的行为相同,更明确地显示了问题:
SELECT
*
FROM
cars
WHERE
(
deleted_at IS NULL
AND
"color" = 'blue'
)
OR
"color" = 'red'
Run Code Online (Sandbox Code Playgroud)
要避免此问题,您应该更改传递Closure的"where"方法.像那样:
$objCars = Car::where(
function ( $query ) {
$query->where("color","blue");
$query->orWhere("color","red");
}
);
Run Code Online (Sandbox Code Playgroud)
然后,系统将执行类似的操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
(
"color" = 'blue'
OR
"color" = 'red'
)
Run Code Online (Sandbox Code Playgroud)
最后一个查询,搜索deleted_at为null的所有汽车以及颜色可以是红色或蓝色的所有汽车,正如我们希望的那样.
Rub*_*zzo 30
使用Eloquent时,软删除功能有效.如果使用查询构建器查询结果,最终会看到所有记录都被删除而不会被删除.
在Laravel 4的当前文档中并不清楚,但是看到软删除的概念只出现在Eloquent ORM - Soft Deleting下而不是在Query Builder下,我们只能假设:软删除仅适用于Eloquent ORM.
我遇到了同样的问题,这里没有任何帮助。
我的问题出在我的构造中,我忘记了调用父构造器:
public function __construct()
{
parent::__construct();
//Rest of my code
}
Run Code Online (Sandbox Code Playgroud)
希望对某人有所帮助!
| 归档时间: |
|
| 查看次数: |
36784 次 |
| 最近记录: |