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

一个人想着一个人 提交于 2019-12-22 01:07:31

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/27747373/in-laravel-how-to-set-up-a-relationship-for-a-likes-table-also-how-to-inclu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!