【问题标题】:Laravel Where Clause To Search In Columns Which Are Not In The DatabaseLaravel Where 子句搜索不在数据库中的列
【发布时间】:2020-10-14 10:35:41
【问题描述】:

我有一张表organisations,其中包含许多列,即idnamecreated_atupdated_at

在我的Organisation 模型中,我通过在模型中添加以下代码来添加自定义属性:

// Add custom attributes
    protected $appends = [
        'device_count',
    ];

和:

public function getDeviceCountAttribute()
    {
        // Count organisation's devices
        $device_count = Device::where('organisation_id', '=', $this->id)->count();
        return $device_count;
    }

在我的控制器中,我试图通过device_count 属性搜索(使用where 子句),但我收到错误,因为这不是我的数据库表中的真实列。

  • 这就是我的搜索方式:
$organisations = Organisation::query();
$organisations = $organisations->where('device_count', '=', 0);
$organisations = $organisations->get();
  • 这是错误:
[2020-10-14 12:29:27] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'device_count' in 'field list'...

是否有替代where 子句的替代方法,以便通过device_count 进行搜索?

【问题讨论】:

    标签: php laravel search eloquent attributes


    【解决方案1】:

    你不能像这样查询属性,它们只存在于模型中,不存在于数据库中。但是,您不需要为此创建 getter。

    Laravel 有一个 withCount() 方法可以用来代替那个属性——这是获取关系计数的正确方法。

    因此具有该属性的查询看起来像

    $organisations = Organisation::withCount('devices')->get();
    

    生成的模型现在将具有device_count 属性,您可以在视图中使用该属性。


    然后在您的查询中,要过滤那些至少具有一定关系计数的记录,您可以这样做

    $organisations = Organisation::has('devices', '=', 0)->get();
    

    由于您正在寻找那些有任何关系的人,您可以将其替换为doesntHave()。包含上面的 sn-p 是为了展示如何查询一组特定的关系计数。

    要仅查询那些没有任何相关设备的设备,只需这样做

    $organisations = Organisation::doesntHave('devices')->get();
    

    这假设您已经在 Organisation 类上定义了 devices 关系。

    public function devices() {
        return $this->hasMany(App\Models\Device::class); // Or App\Device::class if your models are not in the Models namespace/directory
    }
    

    上述方法是 Laravel 的做法 - 因此,您应该从 $appends 中删除您的 getDeviceCountAttribute() 方法和相应的 device_count

    【讨论】:

      【解决方案2】:

      根据您的要求,您希望获得doesnot 中的doesnot 有任何devices 的那些Organisations

      为此,您需要使用doesntHave 方法。

      组织模型中建立关系。

      public function devices() {
          return $this->hasMany('App\Models\Device','organisation_id','id');
      }
      

      现在调用控制器中的mothed/

      $organisations = Organisation::doesntHave('devices')->get();
      

      它将返回那些organisations 不存在的devices

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-19
        • 1970-01-01
        • 2010-09-23
        • 1970-01-01
        • 2012-07-15
        • 1970-01-01
        相关资源
        最近更新 更多