Laravel:如何对belongToMany关系编写连接计数查询?

Laravel:如何对belongToMany关系编写连接计数查询?,laravel,eloquent,query-builder,Laravel,Eloquent,Query Builder,我得到以下信息: 用户,角色,带有角色\用户透视表和归属目录 关系 用户,位置,具有位置\用户透视表和归属关系 用户有两个角色:所有者和园丁 位置有一个“gardeners\u max”字段 在模型位置: protected $appends = ['is_full']; public function getIsFullAttribute() { return $this->attributes['name'] = $this->remainingGardeners(

我得到以下信息:

  • 用户,角色,带有角色\用户透视表和归属目录 关系
  • 用户,位置,具有位置\用户透视表和归属关系
用户有两个角色:所有者和园丁

位置有一个“gardeners\u max”字段

在模型位置:

protected $appends = ['is_full'];

public function getIsFullAttribute()
{
    return $this->attributes['name'] = $this->remainingGardeners() <= 0;
}

public function countGardeners() 
{
    return $this->gardeners()->count();
}

public function remainingGardeners() 
{
    return $this->gardeners_max - $this->countGardeners();
}
我明白了:

[
 {
   name: 'LocationA',
   gardeners_max: 3,
   owners: [...],
   garderners: [...]
   ...
   is_full: false
 }
]
这很酷。但是无法对附加属性执行WHERE子句

Location::where('is_full',true)->get() // Unknown column 'is_full' in 'where clause'
所以我想写一个连接查询,这样我就可以在is_full上执行where子句

我就是找不到路。任何帮助都将不胜感激

重要提示:


我知道filter()方法可以获得结果,但我需要在此处执行单个scopeQuery

从数据库加载对象后,您可以尝试操作
集合

Location::get()->where('is_full', true)->all();
(您必须先使用
get
,然后再使用
all
,否则不确定是否有效)


不确定这是优化的想法。

您可以像这样在位置模型中设置范围

public function scopeFull(Builder $query)
{
    return $query->where('is_full', true);
}
Location::full()->get();
现在你只需要像这样得到所有的位置

public function scopeFull(Builder $query)
{
    return $query->where('is_full', true);
}
Location::full()->get();

谢谢,但由于我刚刚编辑过,我真的需要(并理解)如何编写联接查询库,但它不会像以前那样工作,因为WHERE子句中没有考虑附加属性。。。所以我想我需要一个连接查询