简体   繁体   中英

How do I create different many to many relationships for the same two tables using Eloquent in Laravel

I have 2 tables 'User' and 'Content'. A user can favourite content, so I use a pivot table User_Content to establish the many to many relationship between the user and the content they have favourited. This is fine.

A user can also purchase content. This would be the same relationship as above (User_Content) but would be completely different data.

How do I setup a relationship like this where the relationship between tables is the same but the content is different - can this be done successfully in Laravel using Eloquent? Or is there a completely different way I should be approaching this?

Just set up a user_purchase and user_favorite table both containing user_id and content_id fields

then set up the model

as

class User extends Eloquent{
    public function purchases()
    {
        return $this->belongsToMany('Content','user_purchase');
    }

    public function favorites()
    {
        return $this->belongsToMany('Content','user_favorite');
    }
}

class Content extends Eloquent{

    public function buyers()
    {
        return $this->belongsToMany('User','user_purchase');
    }

    public function favorites()
    {
        return $this->belongsToMany('User','user_favorite');
    }
}

The second column indicates which table to check for the many to many relationship

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM