I have model post. I use this package: https://github.com/cyrildewit/eloquent-viewable
I have accesor in model post:
protected $appends = ['views'];
public function getViewsAttribute()
{
return $this->views()->count();
}
In blade when I foreach
my posts:
@foreach($posts as $post)
Views: {{ $post->views }} {{ trans_choice('trans.views', $post->views)
@endforeach
I get two queries with views
. And if posts 100, then queries will be 200.. For each post I get two same queries. How I can resolve this? If I delete {{ trans_choice('trans.views', $post->views)
Then I get one query.
鉴于views
是Laravel关系,您可以使用withCount
函数“渴望加载”该值 。
$posts = Post::withCount('views')->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.