lundi 28 août 2017

Get all relations for a Model : mixing hasMany and belongsToMany

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 function and be able to see all libraries for user by calling:

$users->libraries

What should I put in this library method?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire