这两个问题..。
假设我有两个模型Owner和Dog,一个主人可以养很多狗。这些狗也有一个领域‘颜色’。
我让所有人都养狗,
$owners = Owner::with('dogs')->get();1.如何获得狗的总数?
在$owners收藏品中,我想要返回狗的总数。
我可以在所有者模型中添加一个计数属性并对其进行求和,但是还有其他方法吗?
2.如何获得黑狗的总数?
我也想要一个黑色的color狗的总数。
谢谢
发布于 2018-06-16 15:31:37
在有效的查询生成器withCount($relation)上有一个特殊的函数,它基本上与$model->relation()->count()相同。不同之处在于,它渴望为集合中的所有模型加载计数,从而获得更好的性能。
$owners = Owner::withCount([
'dogs as dog_count',
'dogs as black_dog_count' => function($query) {
$query->where('color', 'black')
},
])->get();急切地加载关系计数不会加载关系本身。当然,您也可以将with('dogs')链接到函数。
此外,您还可以添加类附加的‘狗_计数’,‘黑_狗_计数’,
class Owner extends Model
{
protected $appends = [
'dog_count',
'black_dog_count',
];
public function getDogCountAttribute()
{
return $this->dogs->count();
}
public function getBlackDogCountAttribute()
{
return $this->dogs->where('color', 'black')->count();
}
}和使用
$owners = Owner::with('dogs')->get();
$allDogsCount = $owners->sum('dog_count');
$allBlackDogsCount = $owners->sum('black_dog_count');或
$allDogsCount = $owners->sum(function ($owner) {
return $owner->dogs->count();
});
$allBlackDogsCount = $owners->sum(function ($owner) {
return $owner->dogs->where('color', 'black')->count();
}); https://stackoverflow.com/questions/50889193
复制相似问题