Results per logged-in user id

Asked

Viewed 345 times

0

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 relationship of the Laravel for these tables

and want to search the person with the user id in the user field

How can I do that?

2 answers

1

If each person corresponds to a user then the Laravel relationship becomes:

No model Pessoa:

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

In the User model:

 public function pessoa() {
            return $this->belongsTo('App\Pessoa');
        }

1


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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.