jeudi 25 avril 2019

Laravel incorporate two type of polymorph relation

tables :

users
  id
  name

roles
  id
  name

model_has_users
  user_id
  model_id
  model_type

I want to make two type of polymorph relations with this three table and their associated models:

1- One To Many polymorphic relation : each user can has multiple users as his children and only one parent

2- Many To Many polymorphic relation : each user can has multiple roles and vise versa

class User extends Model{

public function parent()
{
    return $this->morphTo();
}

 public function chlidren()
{
    return $this->morphMany('App\User', 'model');
}

public function roles()
{
    return $this->morphedByMany('App\Role', 'model');
}

}

class Role extends Model{

public function users()
{
    return $this->morphToMany('App\User', 'model');
}
}

but when i try to get one user's parent i got null. how can this be done. thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire