mardi 20 février 2018

How to get objects of an external model via pivot in Laravel?

I have a many-to-many relationship, and an intermediate table with the RoleUser model. RoleUser has its own relationship with Link model (one to many). I need to get a collection of links using pivot->links. How to do it?

like this (as in the case with withPivot('links'), but for communication with the model)

$role = Role::find(1);
foreach ($role->users as $user) {
   $links = $user->pivot->links;
   dump($links);
}

Pivot (UserRole) model:

class RoleUser extends Pivot {
   public function links() {
    return $this->hasMany('App\Link');
   }
}

Role model

class Role extends Model{ 
   public function users() {
    return $this->belongsToMany('App\User', 'role_user')->using('App\RoleUser');
   }
}

User model

class User extends Authenticatable {
    public function roles() {
    return $this->belongsToMany('App\Role', 'role_user')->using('App\RoleUser');
   }
}

Link model

class Link extends Model {
    public function roleuser(){
     return $this->belongsTo('App\RoleUser');
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire