rtconner / laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a "like" or "favorite" or "remember" feature.
MIT License
401 stars 49 forks source link

Eager loading for liked items #9

Closed TUNER88 closed 8 years ago

TUNER88 commented 9 years ago

I want to display a table with likeable items, each row should have like/unlike button. To get current state of like/unlike for each row, I have make new SQL request for each row. $article->liked();

How can reduce the number of queries?

My query for the grid:

$query = (new File())->with('user')->with('organisation')->with('likes')->newQuery();

Many thanks in advance.

screen shot 2015-07-17 at 11 52 15

guyyosan commented 9 years ago

you can just do this in your with...

with('user', 'organisation', 'likes')
Akeri commented 8 years ago

I'm having the same issue and my query is:

$posts = Post::with('categories', 'tagged', 'likeCounter', 'likes')
            ->where('publish_date', '<=', date('Y-m-d H:i:s'))
            ->orderBy('publish_date', 'desc')->get();

Getting one query foreach $post->liked($user_id)

What am I doing wrong? Thanks in advance

federico77 commented 7 years ago

Hello, I have the sam kind of issue and the @guyyosan trick of using ->with('likes') is not working. I believe the issue lies within the "liked()" method in the trait as it states:

return (bool) $this->likes()
    ->where('user_id', '=', $userId)
    ->count();

I'm not an expert of eager loading just yet but I guess this method hits the DB no matter what. Does anyone know of a workaround or an existing fix to this behaviour?

Thanks in advance.

mydnic commented 2 years ago

No solution for this ?