As described in the manual https://laravel.com/docs/5.4/eloquent-relationships, in One to One relations you must create a function that returns a namespace object \Illuminate\Database\Eloquent\Relations\
, this namespace has several types of relationships.
Assembling the functions where the person belongs to a user, therefore in the model Person:
public function user() {
return $this->belongsTo(App\User::class);
}
And a user has a person, this way in the model User:
public function pessoa() {
return $this->hasOne(App\Pessoa::class);
}
The relationship 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 solve the name of the foreign keys 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
even, it is necessary to pass to the functions the custom name of the key:
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 recover the person or user related to a record, just call the function name. For example:
$p = Pessoa::find(xx);
return $p->user->email;
$u = User::find(yy);
return $u->pessoa->sobrenome;