Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Having a hasMany() as well as a hasOne() relationship on the same model?

I've got a Company model in which I would like to define two relationships with the User model:

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

  public function administrator(){
     return $this->hasOne('App\User', 'superuserid');
  }

I have a superuserid field in my companies table in the database, which is a foreign key to the id of the users table.

I just want to know if this is at all a good strategy or even possible?

like image 774
omrakhur Avatar asked Jan 16 '17 09:01

omrakhur


1 Answers

Yes, it is a good strategy and it is possible.

In your model you can define as much relations as your model needs. And those relations can be of different types (hasOne, hasMany, belongsTo, etc).

In your case, since the company has multiple users and belongs to a super user, we have two different relations, so, obviously, we need to create two methods in the model to represent these two relations.

Another example: the relation between you and your father. Let's say that there is this implementation of a User model:

class User extends Model
{

  public function children()
  {
    return $this->hasMany(User::class, 'id_parent');
  }

  public function dad()
  {
    return $this->belongsTo(User::class, 'id_parent')->where('gender', 'male');
  }

}

Here a User can has many children but belongs to just one dad.

like image 79
Artenes Nogueira Avatar answered Sep 26 '22 07:09

Artenes Nogueira