Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top