0
votes

I got the following models:

  • User
  • UserGroup
  • Item

Now every user has a belongsToMany relation to Item with pivot:

    public function items()
    {
        return $this->belongsToMany(Item::class)
            ->withPivot('value');
    }

This is the structure of item:

Item

  • title
    • pivot:
      • value

Example

User

  • name: Tim
  • items:
    • title: car
    • value (pivot): 2

Now it's getting tricky: I'd like to use User also in the model UserGroup - and each User should have many Items with a new pivot table, that's not identical to the pivot table, the Item has, when it's a pivot of User.

Example

UserGroup

  • name: Party-Group
  • users:
    • name: Tim
    • items:
      • title: car
      • value (pivot): 3

My approach

So I think, the only possible solution would be to create something like a new model called UserGroupUser (extended from User) with a relation to UserGroupUserItems (extended from Item).

But maybe there's a smarter way to do that?

1

1 Answers

0
votes

You could create a users() method on the User group like so:

class UserGroup extends Model
{
    public function users()
    {
        return $this->hasMany(User::class);
    }
}

// Then to retrieve your data:
$groups = UserGroup::with('users.items')->get();
dd($groups);