eager-load-pivot-relations
eager-load-pivot-relations copied to clipboard
Idea: Possible to eager load pivot relations on a model instance?
Is it possible to load pivot relations on a model instance?
Taking the example on the README, say you have a controller method:
public function index(Plan $plan)
{
}
It would be great to be able to do something like:
$plan->load('items.planItem.unit');
or better yet:
$items = $plan->items()->orderBy('name')->with('planItem.unit')->get();
to return that to the view
thanks!
@empresarrollo I believe that should work
@ajcastro
You are right. with $plan->load('items.planItem.unit');
I've made it work.
But I cannot eager load the pivot relation going from "items()":
When I do
$items = $plan->items()->orderBy('name')->with('planItem.unit')->get();
i got:
Call to undefined relationship [planItem] on model [App\Item].
I don't think it's possible.
I have the same issue. Any updates?
@empresarrollo @lidoma , sorry for late reply.
Here's how to make it work.
You need to define a hasOne
planItem()
relation in Item
model. That way we, can eagerload the planItem
relation model coming from Item
model.
class Item extends Model
{
public function planItem()
{
return $this->hasOne(PlanItem::class);
}
}
Keep in mind that item
has many planItem
in actual, but since we only care for one planItem
for each plan
, then we define a hasOne
planItem
relation instead. We will just need to pass the plan_id
in the eager load query to make sure we are getting the correct planItem
for the plan
and item
:
$items = $plan->items()
->with([
'planItem' => function ($query) {
$query->where('plan_id', $plan->id);
},
'planItem.unit'
])
->get()
dd($items->toArray());
/*
[
[
'id' => '',
'name' => '',
'description' => '',
'planItem' => [
'plan_id' => '',
'item_id' => '',
'unit_id' => '',
'qty' => '',
'price' => '',
'unit' => [
'id',
'name' => '',
'description' => '',
],
],
], [
'id' => '',
'name' => '',
'description' => '',
'planItem' => [
'plan_id' => '',
'item_id' => '',
'unit_id' => '',
'qty' => '',
'price' => '',
'unit' => [
'id',
'name' => '',
'description' => '',
],
],
],
]
*/
I haven't tested it yet but I believe it should work