I have a users table with primary_key id and I have a people table with a user field
I want to understand how to use the laravel relationship for these tables
and I want to fetch the person with the userid in the user field
How can I do this?
I have a users table with primary_key id and I have a people table with a user field
I want to understand how to use the laravel relationship for these tables
and I want to fetch the person with the userid in the user field
How can I do this?
As described in the link manual, in One to One relationships you must create a function that returns an object from namespace \Illuminate\Database\Eloquent\Relations\
, this namespace has many types of relationships.
Assembling the functions where the person belongs to a user, therefore in the Person model:
public function user() {
return $this->belongsTo(App\User::class);
}
And a user has one person, this way in the User model:
public function pessoa() {
return $this->hasOne(App\Pessoa::class);
}
The relation of type belongsTo
implies that the foreign key exists in this table, so according to its description, in this case we read that Person belongs to a User.
And because Eloquent tries to resolve the foreign key name according to the name of the related classes, it would be interesting to use the name user_id
for the field in the person table. If you want to use user
yourself, you must pass the custom key name to the functions:
Model Person :
public function user() {
return $this->belongsTo(App\User::class, 'user');
}
Model User :
public function pessoa() {
return $this->hasOne(App\Pessoa::class, 'user');
}
Now to retrieve the person or user related to a record, simply call the function name. For example:
$p = Pessoa::find(xx);
return $p->user->email;
$u = User::find(yy);
return $u->pessoa->sobrenome;
If each person corresponds to a user then the laravel relationship is:
In the model Person:
public function user() {
return $this->belongsTo('App\User');
}
In the User model:
public function pessoa() {
return $this->belongsTo('App\Pessoa');
}