我有一个Orders表,它与一个移动表有关系,我经常这样做来计算每个订单的几个公共值:
$warehouse = 7;
$order = Order::find(16111);
$entries = Movement::selectRaw("SUM(gross) AS total_gross")
->selectRaw("SUM(net) AS total_net")
->selectRaw("SUM(qty) AS total_qty")
->where('order_id', $order->id)
->where('to_id', $warehouse)
->first();
$exits = Movement::selectRaw("SUM(gross) AS total_gross")
->selectRaw("SUM(net) AS total_net")
->selectRaw("SUM(qty) AS total_qty")
->where('order_id', $order->id)
->where('from_id', $warehouse)
->first();是否可以创建一个自定义函数来查询DB,这样做如下:
$warehouse = 7;
$entries = Order::find(16111)->entries($warehouse);
$exits = Order::find(16111)->exits($warehouse);如果是的话,如何才能做到呢?
谢谢你的帮助..。
发布于 2021-05-24 19:35:37
绝对一点儿没错。您要查找的内容称为本地查询Scopes;它允许您避免重复代码中的复杂查询。
本地作用域允许您定义公共的查询约束集,您可以轻松地在整个应用程序中重用这些约束。
在您的模型中编写您的本地查询范围,您将不再重复这段代码(DRY原则)。
这里有一个例子给你一个想法,你需要调整它来满足你的需要。
订单模型中的:
public function scopeEntries($query)
{
$warehouse = $this->warehouse; // Take advantage of Eloquent wherever you can
return $query->movements()->selectRaw("SUM(gross) AS total_gross")
->selectRaw("SUM(net) AS total_net")
->selectRaw("SUM(qty) AS total_qty")
->where('to_id', $warehouse->id);
}
public function scopeExits($query)
{
$warehouse = $this->warehouse; // Take advantage of Eloquent wherever you can
return $query->movements()->selectRaw("SUM(gross) AS total_gross")
->selectRaw("SUM(net) AS total_net")
->selectRaw("SUM(qty) AS total_qty")
->where('from_id', $warehouse->id)
->where('to_id', $warehouse->id);
}现在,在您的代码中,您可以简单地调用$order->entries()->first()来检索第一个条目,但也可以调用$order->exits()->get()检索所有出口。
https://stackoverflow.com/questions/67677469
复制相似问题