I have 4 tables with relations like on the picture . I have also 2 functions in User model:
public function getUserSchools(){
return $this->belongsToMany(Schools::class, 'user_has_schools', 'user_id', 'school_id');
}
public function getUserRoles(){
return $this->belongsToMany(Roles::class, 'user_has_schools', 'user_id', 'role_id');
}
They work fine, but I want to merge results of them - I need to get schools of this user with his role in every school (for example: [Primary School, Teacher], [High School, Boss], etc.). How can I reach that result? Maybe this is a trivial question, but I'm just starting my adventure with Laravel. :)
check out the Laravel polymorphic relationship https://laravel.com/docs/5.8/eloquent-relationships#many-to-many-polymorphic-relations
sample :
class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
don't mind the sample methods
class Tag extends Model
{
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
public function links()
{
return $this->morphedByMany('App\Links', 'taggable');
}
public function forum()
{
return $this->morphedByMany('App\Forums', 'taggable');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.