Get all relations for a Model : mixing hasMany and belongsToMany

194 Views Asked by At

It's about "libraries" and "users", but it can be seen as a more generic case.

  • I have a Library model associated with a libraries table.
  • The libraries table has a creator_id which is a reference to the users table.
  • There is also a pivot table library_user for all the users who can see a library.

So I can get all the libraries associated to users via the pivot table by creating a method in User model like this:

public function librariesAssociatedViaPivot()
{
    return $this->belongsToMany(Library::class);
}

I can also create a function to get the libraries created by a User:

public function librariesCreatedByUser()
{
    return $this->hasMany(Library::class);
}

But What I want is the libraries the User has created + the libraries the User can see. In other words, I want to mix the two functions and be able to see all libraries for a User by calling:

$users->libraries

What should I put in this library method?

public function libraries()
{
    // ... ?
}

Side note: I don't want to add the creator in the pivot table.

1

There are 1 best solutions below

4
On

So $user->librariesAssociatedViaPivot and $user->librariesCreatedByUser both return a Collection of Librarys? And you want to combine both? In that case, simply do this:

public function libraries()
{
    return $this->librariesAssociatedViaPivot->merge($this->librariesCreatedByUser);
}

and use $user->libraries().