所以,我有这种关系:
public function publishedAlbums()
{
return $this->hasMany('Album')->where('is_published', true)->has('photos');
}
public function getPhotoCountAttribute()
{
$count = 0;
foreach ($this->publishedAlbums as $album)
{
$count += $album->photos->count();
}
return $count;
}
它得到一个准确的计数,但它导致我的7张专辑的7个查询,即使我正在急切加载has('Photos')。我的理解是,如果我这样做,只需要一个查询。我做错了什么?