eager-load-pivot-relations icon indicating copy to clipboard operation
eager-load-pivot-relations copied to clipboard

Idea: Possible to eager load pivot relations on a model instance?

Open empresarrollo opened this issue 4 years ago • 4 comments

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 avatar May 11 '20 21:05 empresarrollo

@empresarrollo I believe that should work

ajcastro avatar May 12 '20 01:05 ajcastro

@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.

empresarrollo avatar May 12 '20 12:05 empresarrollo

I have the same issue. Any updates?

lidoma avatar Jul 05 '20 13:07 lidoma

@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

ajcastro avatar Oct 01 '20 04:10 ajcastro