Dumitru
Dumitru

Reputation: 2183

Laravel two queries, how do one query?

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.

Upvotes: 0

Views: 57

Answers (1)

ceejayoz
ceejayoz

Reputation: 180176

Given that views is a Laravel relationship, you can use the withCount function to "eager load" the value.

$posts = Post::withCount('views')->get();

Upvotes: 3

Related Questions