Laravel does not load the relationships correctly from belongsTo

0

At the database level, all the users have a profile assigned, when it comes to consulting from the profile model, the users bring it well, but when consulting from the user model the profiles with with () loads only 1 relation for each type of profile and does not load anything for the rest.

User

public function Perfil(){
    return $this->belongsTo('App\Perfil','perfil_fk');
}

Profile

public function Users(){
    return $this->hasMany('App\User','perfil_fk','id');
}

Other relationships with users work well, including many to many, the user's model is the one that generates authentication by default in laravel.

The problem is with egaer loading At the moment I had to do another query to load the profile, but I really need to do it with -> with ()

$user->Perfil = Perfil::select('nombre','activo')->where('id', $user->perfil_fk)->get()[0];

In the database if the rows are related:

    
asked by César Alejandro M 04.07.2018 в 23:01
source

1 answer

0

The problem is that you have the relationships reversed and also I think you are using a relation hasMany that does not correspond, since a user should have only 1 profile. the tables should be defined like this:

  

users:
      - id
      - name
      - ...
profiles:
      - id
      - user_id
      - ...

and the models

User :: class
Relation One To One

public function perfil() {
    return $this->hasOne('App\Perfil'); // por convencion busca el campo user_id
}

Profile :: class
Relation One To One (inverse)

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

and in this way when making your query should appear the users with their respective profile.

User::with('perfil')->get() 

You have many examples in the documentation on this topic.

    
answered by 05.07.2018 в 05:49