2
votes

I'm trying to see what the best way to do the following.

I have 3 tables: users, items and item_user.

users and items table are pretty generic, id and a few columns to hold whatever data.

item_user table has the following structure id
item_id
user_id
user_type [ 1 - Owner | 2 - Follower | 3 - Something else ]

Relationships: Each Item has 1 Owner (user type)
Each Item has many followers
Each User can own many Items
Each User can follow many Items

I would like to have the Owner and Followers be the Users table so I don't need to replicate user data. I created a pivot table of item_id, user_id and user_type to hold these relationships.

So the question is how to I do this in Laravel Eloquent?

Item Model looks like:

public function user() {
    return $this->belongsToMany('Users');
    // This isn't actually correct since it belongs to only one User but not sure how to specify a where user_type = 1;
    // return $this->belongsTo('User');
}

User Model looks like:

public function item() {
    return $this->hasMany('Item');
}

Thanks!

1

1 Answers

1
votes

You can just append the condition to your belongsToMany declaration:

public function user() {
    return $this->belongsToMany('Users')->where('user_type', 1);
}

This will return only the User entries that have user_type = 1 in your pivot table. And just to make it more clear you could name the method owner() instead of user() to reflect the added condition.