【问题标题】:How can I define default where condition for all select queries in my models?如何为模型中的所有选择查询定义默认 where 条件?
【发布时间】:2019-05-25 06:38:18
【问题描述】:

我需要在我的模型中设置默认 where 条件。

所以实际上我必须在我的所有选择查询中设置它。

查询如下:

->where('status','active')

【问题讨论】:

    标签: mysql laravel model eloquent default


    【解决方案1】:

    您可以使用全局范围: https://laravel.com/docs/5.7/eloquent#global-scopes

    将其写入您要使用条件查询的模型中

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
    
        static::addGlobalScope('status', function (Builder $builder) {
            $builder->where('status', 'active');
        });
    }
    

    【讨论】:

      【解决方案2】:

      你可以在模型中使用 laravel 作用域(局部作用域或全局作用域):

      全局范围示例:

      在 Model.php 中:

       protected static function boot()
          {
              parent::boot();    
              static::addGlobalScope('status', function (Builder $builder) {
                  $builder->where('status', 'active');
              });
          }
      

      本地范围示例:

      在 Model.php 中

      public function scopeIsActive($query)
          {
              return $query->where('status', 'active');
          }
      

      在控制器中:

      Model::isActive()->get();
      

      source

      【讨论】:

        【解决方案3】:

        你应该试试这个:

        你的模特:

        class News extends Eloquent {
           public function scopeStatus($query)
            {
             return $query->where('status', '=', 1);
            }
         }
        

        你的控制器:

        $news  = News::status()->get();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-01
          • 1970-01-01
          • 2021-08-03
          • 1970-01-01
          • 1970-01-01
          • 2016-01-23
          • 2012-12-16
          • 2014-08-20
          相关资源
          最近更新 更多