在Laravel-Eloquent模型中,是否可以设置model,使其始终使用默认的Where子句,除非另有指定。
例如,转动这个:
$activeRecords = Records::where('status','active')->get()
进入:
$activeRecords = Records::all();
但是,如果我想获得非活动记录,我必须告诉它这样做,
您可能需要查看SoftDelete Trait(http://laravel.com/docs/5.1/eloquent#soft-删除)这与您的状态标志不完全相同,但这是一种非常干净的方式。
通过将deleted_at列添加到模式中,并在模型中引入特征use SoftDeletes;
,您可以删除记录,但它们实际上不会从数据库中删除。
如果您执行了Records::all()
,那么您将看到所有尚未删除的记录,如果您希望使用withTrashed
方法访问已删除的记录。
正如@ChetanAmeta所建议的,我将覆盖模型类中的newQuery
方法:
class Records extends Eloquent {
public function newQuery($excludeDeleted = true) {
return parent::newQuery($excludeDeleted = true)
->where('status', 'active');
}
}