Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship between table is not working

I have two tables user and profile. Profile table had user_id as foreign key. I have related the two tables.

In tinker I can see that relation is made but in code its not fetching the details from other table.

I have also tried

return $this->belongsTo('User::class');

User Model

public function profile() {
    return $this->hasOne('Profile');
}

Profile Model

public function user() {
    return $this->belongsTo('User');
}
like image 269
tru.d Avatar asked Nov 18 '25 02:11

tru.d


2 Answers

I see two things that are not completely right.

In tinker to obtain the profile of user insert this lines:

$user = User::find([user_id]);

And then :

$user->profile();

If you want to associate the ::class you should use:

return $this->belongsTo(User::class);

If you want to use the string association should use:

return $this->belongsTo('App\User');
return $this->hasOne('App\Profile');

Another tip is every time you change a controller you have to close and open tinker again

like image 119
Pedro Costa Avatar answered Nov 21 '25 10:11

Pedro Costa


Try to specify keys for hasOne and belongsTo method as below:

 $this->hasOne('Profile', 'foreign_key', 'local_key');

 $this->belongsTo('User', 'foreign_key', 'local_key');

Look also on one to one relation: https://laravel.com/docs/6.x/eloquent-relationships#one-to-one

like image 42
Adam Kozlowski Avatar answered Nov 21 '25 08:11

Adam Kozlowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!