Home > Net >  Laravel Model hasMany - getting too may results
Laravel Model hasMany - getting too may results

Time:07-25

I'm learning Laravel, so I'm quite new.

I have 2 Models: House and Translation.

My House Model:

use HasFactory;

protected  $guarded = ['id'];

public function trans(){
    return $this->hasMany(Translation::class);
}

}

My Translation Model:

function House(){
    return $this->belongsTo(House::class);
}

}

When I do in the controller something like ($id=2 e.g) :

$house  = House::find($id)::with('trans')->get();

I get a result with all houses (there are currently 2 in the DB). When I just do the query "House::find($id)->get()" it works fine.

What part am I missing?

CodePudding user response:

::with('trans') returns completely new query and forgets everything about your ::find($id)

CodePudding user response:

you need to use load method.

$house = House::find($id);

$house->load('trans');

CodePudding user response:

What happens is, House::find($id) is a method that returns the element by its primary key. Then, the ::with('trans') gets the result, sees the House class and starts creating a new query builder for the Model. Finally, the ->get() runs this new query and the end result is what is return for the $house value.

You have two options that will result to what you want to do.

First one is, to find the house entry and then load its relation

$house = House::find($id);
$house->load('trans');

The second option is this:

$house = House::where('id',$id)->with('trans')->first();

The second one is a query builder that results to the first element with id = $id, and load its relation with translations.

You can check for more details in the laravel documentation. They have a very well-written documentation and the examples help a lot.

  • Related