Search

Eager Load Pivot Relations - Laravel News

boonoor.blogspot.com

Arjon Jason Castro created a package for eager-loading pivot relations (BelongsToMany), which can help avoid N+1 queries on the pivot model.

Once you’re model has the EagerLoadPivotTrait you can eager load them as follows:

$plan = Plan::with('items.pivot.unit')->find($id);
$plans = Plan::with('items.pivot.unit')->get();

// Load other relations as well
$plans = Plan::with([
  'items.pivot.unit',
  'items.pivot.unit.someRelation',
])->get();

You can also customize the name of the pivot model accessor:

class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->withPivot('unit_id', 'qty', 'price')
            ->using('PlanItem')
            ->as('planItem');
    }
}

$plan = Plan::with('items.planItem.unit')->get();

foreach ($plan->items as $item) {
    echo $item->planItem->unit->name
}

Check out the package’s readme for installation instructions and documentation. The author has an example project to demonstrate using this package.

Filed in: News

Let's block ads! (Why?)



"load" - Google News
October 02, 2020 at 08:00PM
https://ift.tt/36plIXZ

Eager Load Pivot Relations - Laravel News
"load" - Google News
https://ift.tt/2SURvcJ
https://ift.tt/3bWWEYd

Bagikan Berita Ini

0 Response to "Eager Load Pivot Relations - Laravel News"

Post a Comment

Powered by Blogger.