【问题标题】:Laravel model record retrieveLaravel 模型记录检索
【发布时间】:2020-03-31 04:27:53
【问题描述】:

现在我有一个名为users 的表,我在users 表中有一个名为is_active 的列。如果我可以在模型中编写一个代码,当我查询 Users::all() 时,它只会得到 is_activetrue ?如果我想获得is_activefalse 的记录,我可以写Users::withInActive()->get() 吗?

这就像 deleted_at 在 laravel 中的工作方式。

【问题讨论】:

    标签: laravel eloquent model


    【解决方案1】:

    您可以为此使用global scopes。定义它们后,它将自动应用于查询。为此,我们可以覆盖模型中的boot 方法。

    仅获取活跃用户:

    use Illuminate\Database\Eloquent\Builder;
    
    class User extends Model{
       ...
       static function boot(){
            parent::boot();
             static::addGlobalScope('active', function (Builder $builder) {
                $builder->where('is_active', true); // or 1 if you are using tinyint 
            });
       }
    
    }
    

    获取非活跃用户:

    要获取活跃用户,您可以跳过附加的范围。

    User::withoutGlobalScope('active')->get();
    

    【讨论】:

      【解决方案2】:

      只需在查询中使用 where() 函数即可。

      Users::where("is_active", true)->get();
      

      像这样。

      编辑:使用范围

      在你的模型中

      public function scopeWithInActive($query)
      {
          return $query->where('in_active', true);
      }
      

      你可以像这样使用你的范围

      $users->withInActive()->get()
      

      【讨论】:

      • 我知道这一点。但是因为它已在多个地方使用过,所以我想知道是否可以在控制器中的上述查询的模型级别上执行此操作。
      • 哦。对不起。我误解了你的问题。您可以在 eloquent 模型上使用范围。 laravel.com/docs/5.8/eloquent。检查查询范围部分
      猜你喜欢
      • 2016-05-19
      • 1970-01-01
      • 2019-06-03
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多