在post 的帮助下,我能够解决这个问题。这就是我所做的:
零件模型
创建两个关系orderPartsCount和projectPartsCount,添加属性calculatedStock对它们求和并提供一种简单的检索方式。
public function orderPartsCount()
{
$a = $this->orders();
$a1 = $a->selectRaw($a->getForeignKey() . ', sum(count) as stock')
->where('done', '>', 0)
->groupBy($a->getForeignKey()
);
return $a1;
}
public function projectPartsCount()
{
$b = $this->projects();
$b1 = $b->selectRaw($b->getForeignKey() . ', sum(count) as 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 they are listed as positive counts but shall reduce the stock
return $orders + ( $projects * -1);
}
部分控制器
在控制器中急切加载 orderPartsCount 和 projectPartsCount。
public function index()
{
return View::make('parts.index', [
'parts' => Part::with('category', 'location', 'orderPartsCount', 'projectPartsCount')
->orderBy('description_no')
->paginate(100)
]);
}