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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With