简体   繁体   English

Laravel默认在哪里发牢骚

[英]Laravel Default Where caluse

In Laravel Eloquent model, is it possible to set the Model so it would always use a default Where clause unless specified otherwise. 在Laravel Eloquent模型中,可以设置模型,以便除非另有说明,否则它将始终使用默认的Where子句。

So for example turn this: 因此,例如,将其打开:

$activeRecords = Records::where('status','active')->get()

Into this: 变成这个:

$activeRecords = Records::all();

But if I would like to get inactive records I would have to tell it todo so 但是,如果我想获取不活动的记录,则必须告诉它这样做

As @ChetanAmeta suggested, I would overwrite newQuery method in the model class: 如@ChetanAmeta所建议,我将覆盖模型类中的newQuery方法:

class Records extends Eloquent {

    public function newQuery($excludeDeleted = true) {
        return parent::newQuery($excludeDeleted = true)
            ->where('status', 'active');
    }

}

You might want to take a look at the SoftDelete Trait ( http://laravel.com/docs/5.1/eloquent#soft-deleting ) its not exactly the same as with your status flag but is quite a clean way of doing it. 您可能要看一下SoftDelete特性( http://laravel.com/docs/5.1/eloquent#soft-deleting ),它与状态标志并不完全相同,但是是一种很干净的方法。

By adding the deleted_at column to your schema and introducing the trait use SoftDeletes; 通过将Deleted_at列添加到您的模式并引入特征,请use SoftDeletes; on your model you can then delete records but they won't actually be removed from the database. 然后,您可以在模型上删除记录,但实际上不会从数据库中删除它们。

If you then did Records::all() you would see all records that haven't been deleted if you want the ones that have been deleted you can access then with the withTrashed method. 如果您随后执行Records::all()那么您将看到所有尚未删除的记录,如果您希望已删除的记录可以使用withTrashed方法访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM