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

[SOLVED] How to order posts by like date? #23

Closed liorocks closed 8 years ago

liorocks commented 8 years ago

I need to order posts by DESC of when the user has liked them.

I've got the following code:

Post::whereLiked($userId)->paginate();

I tried something like this, but got me nowhere.

Post::whereHas('likes', function($q) use($userId) {
            return $q->where('user_id', $userId)->orderBy('created_at', 'DESC');
        })->paginate();

What i'm doing wrong here?

liorocks commented 8 years ago

Ok, I've managed to do this by myself.

I've added this method to the Post model:

public static function getLikes($user_id) {
        return (new static)
            ->join('likeable_likes', 'posts.id', '=', 'likeable_likes.likable_id')
            ->select('posts.*')
            ->where('likeable_likes.user_id', '=', $user_id)
            ->orderBy('likeable_likes.created_at', 'DESC');
    }

And the usage is:

Post::getLikes($user_id)->get();

If someone has a better solution, please post it.