laravel 5 - Eager loading sum from two pivot tables with Eloquent -


i have part entity has many-to-many relationship order , project. pivot tables contains quantity field might have positive or negative value, , adding sums of both pivot tables, specific part, current stock.

i able this, n+1 problem. , having hard time figuring out how can eager loading. i've read post, don't understand how adapt needs.

so looking way provide eager loadable stock property on part model, suggestions how can accomplish this?

i able figure out of post. did:

part model

create 2 relationship orderpartscount , projectpartscount, add attribute calculatedstock sum them , provide easy way of retrieving.

public function orderpartscount() {     $a = $this->orders();     $a1 = $a->selectraw($a->getforeignkey() . ', sum(count) stock')             ->where('done', '>', 0)             ->groupby($a->getforeignkey()         );      return $a1; }  public function projectpartscount() {     $b = $this->projects();     $b1 = $b->selectraw($b->getforeignkey() . ', sum(count) stock')             ->where('status', '>', 0)             ->groupby($b->getforeignkey()         );      return $b1; }  public function getcalculatedstockattribute() {     $orders = $this->orderpartscount->first() ? $this->orderpartscount->first()->stock : 0;     $projects = $this->projectpartscount->first() ? $this->projectpartscount->first()->stock : 0;      // invert project parts, since listed positive counts shall reduce stock     return $orders + ( $projects * -1); } 

part controller

eager load orderpartscount , projectpartscount in controller.

public function index() {     return view::make('parts.index', [         'parts' => part::with('category', 'location', 'orderpartscount', 'projectpartscount')             ->orderby('description_no')             ->paginate(100)     ]); } 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -