Search code examples
laraveleloquentrelationships

In Laravel, how to set up a relationship for a "likes" table? Also, how to include that information in a query?


I have three tables: users, ideas, and ideas_likes. The ideas_likes table looks like:

ideas_likes
------------
id        primary key
user_id   foreign key
idea_id   foreign key
liked     boolean

There's already a one-to-many relationship set up between users and ideas. It looks something like this:

class User extends Ardent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $table = 'users';

    public function ideas()
    {
        return $this->hasMany('Idea');
    }   

}

Similarly, the idea model looks like this:

class Idea extends Ardent {

    protected $table = 'ideas';

    public function user()
    {
        return $this->belongsTo('User');
    }

}

My first question is: How do I create the IdeaLike model? And once that is finished, using Eloquent, how do I retrieve all liked ideas for a user?

===========================================================================

Lucasgeiter's updated solution worked great.


Solution

  • First, there's no need to create an IdeaLike model. You just need a many-to-many relationship

    User

    public function ideas(){
        return $this->belongsToMany('Idea', 'ideas_likes')->withPivot('liked');
    }
    

    Idea

    public function users(){
        return $this->belongsToMany('User', 'ideas_likes')->withPivot('liked');
    }
    

    (By adding withPivot I tell Laravel that I want to have the liked column from the pivot table included in the result)

    Usage

    $user = User::find(1);
    $likedIdeas = $user->ideas()->where('liked', true)->get();
    


    By the way: You don't need to specify the $table if it is the plural of the model name.

    Update

    It looks like you actually really do need both, a one-to-many and a many-to-many relation.

    So your final relations would look like this:

    User

    public function ideas(){
        return $this->hasMany('Idea');
    }
    
    public function liked(){
        return $this->belongsToMany('Idea', 'ideas_likes')->withPivot('liked');
    }
    

    Idea

    public function likes(){
        return $this->belongsToMany('User', 'ideas_likes')->withPivot('liked');
    }
    
    public function user(){
        return $this->belongsTo('User');
    }
    

    (I just chose names for the relations that made kind of sense to me. You can obviously change them)

    Usage

    Liked ideas by a certain user: (id = 1)

    $ideas = Idea::where('user_id', 1)->whereHas('likes', function($q){
        $q->where('liked', true);
    })->get();