Home > Net >  Laravel - How use HasMany
Laravel - How use HasMany

Time:03-04

I have a little problem with model relationships.

I have a Users table and a Appartaments table, with a hasmany relationship linked from the ref_user field(Users) to the agent field(Appartaments). Neither is a primary key.

In my User model I have:

    public function appartaments(){
    return $this->hasMany(Appartament::class,'agent','ref_user');
}
public function idAppartaments($id){
    return User::find($id)->appartaments;
}

In my controller I have:

public function getAppUser($ref_user){
    $id = User::select('id')->where('ref_user',$ref_user)->get();
    $appartaments = User::idAppartaments($id);
    return $appartaments;

When I try the route however, I get an error that the appartaments property does not exist.

CodePudding user response:

This is the proper way to do so: in your User Model:

public function appartaments(){
    return $this->hasMany(Appartament::class,'agent','ref_user');
}

in your controller:

public function getAppUser($ref_user){
    $user = User::with('appartaments')->where('ref_user',$ref_user)->first();
    $appartaments = $user ? $user->appartaments : null;
    return $appartaments;
}

CodePudding user response:

Instead of your controller method:

public function getAppUser($ref_user){
$id = User::select('id')->where('ref_user',$ref_user)->get();
$appartaments = User::idAppartaments($id);
return $appartaments;

The method should be:

public function getAppUser($ref_user){
$id = User::select('id')->where('ref_user',$ref_user)->get();
$appartaments = $id->appartaments();
return $appartaments;
  • Related