finchy70
1 year ago

Raw sql to Eloquent

Posted 1 year ago by finchy70

I have 3 models. Post User Favorite

Post has posts and the following relationship

public function favourite()
    {
        return $this->hasMany(Favourite::class);
    }

User is users and the following relationship

public function favourite()
    {
        return $this->hasMany(Favourite::class);
    }

Favorite is user_id , post_id when a user likes a post. and the following relationships

class Favourite extends Model
{
    public function post()
    {
        return $this->hasMany(Post::class);
    }

   public function user()
   {
        return $this->hasMany(User::class);
    }

This raw mySql query returns all the posts favorited by a user.

select posts.* from users, posts, favourites where(users.id = '1' && users.id = favourites.user_id && favourites.post_id = posts.id);

The '1' in the query will be the value of Auth->user()->id Can I create an eloquent query to tidy thisup or if not how do I use this query in laravel.

Thanks Paul

Please sign in or create an account to participate in this conversation.