[英]Laravel two queries, how do one query?
I have model post. 我有模特职位。 I use this package: https://github.com/cyrildewit/eloquent-viewable
我用这个包: https : //github.com/cyrildewit/eloquent-viewable
I have accesor in model post: 我在模型帖子中有accesor:
protected $appends = ['views'];
public function getViewsAttribute()
{
return $this->views()->count();
}
In blade when I foreach
my posts: 在刀片时,我
foreach
我的帖子:
@foreach($posts as $post)
Views: {{ $post->views }} {{ trans_choice('trans.views', $post->views)
@endforeach
I get two queries with views
. 我得到两个带有
views
查询。 And if posts 100, then queries will be 200.. For each post I get two same queries. 如果帖子100,那么查询将是200。对于每个帖子,我都会得到两个相同的查询。 How I can resolve this?
我该如何解决? If I delete
{{ trans_choice('trans.views', $post->views)
Then I get one query. 如果我删除
{{ trans_choice('trans.views', $post->views)
然后我得到一个查询。
鉴于views
是Laravel关系,您可以使用withCount
函数“渴望加载”该值 。
$posts = Post::withCount('views')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.