我得到了以下内容:
用户有2个角色:所有者&园丁
位置有一个' gardeners_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();
}
现在,这样做:
Location::all();
我明白了:
[
{
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
答案 0 :(得分:0)
从数据库加载对象后,您可以尝试操作Collection
:
Location::get()->where('is_full', true)->all();
(您必须首先使用get
然后all
,否则不确定是否有效)
不确定它是否已经过优化。
答案 1 :(得分:0)
您可以在此位置模型中制作范围
public function scopeFull(Builder $query)
{
return $query->where('is_full', true);
}
现在你得到这样的所有位置
Location::full()->get();