减少前面的sql查询次数
orders
id - integer
client_id - integer
clients
id - integer
name - string
accounts
id - integer
client_id - integer
amount - integer
控制器
$orders = Order::with(['transaction', 'client', 'delivery', 'address'])
->latest()->paginate(50);
return view('admin.order.index', compact('orders'));
前端
<td class="text-center">
<strong>{{$item->client->invoice}}</strong>
</td>
客户端模型
public function getInvoiceAttribute()
{
return $this->account()->sum('amount');
}
我不知道如何使用有很多通过。 或者说遇到这种情况怎么解决 我不需要前台账户,但我需要金额总和
orders
id - integer
client_id - integer
clients
id - integer
name - string
accounts
id - integer
client_id - integer
amount - integer
Controller
$orders = Order::with(['transaction', 'client', 'delivery', 'address'])
->latest()->paginate(50);
return view('admin.order.index', compact('orders'));
FrontEnd
<td class="text-center">
<strong>{{$item->client->invoice}}</strong>
</td>
Client Model
public function getInvoiceAttribute()
{
return $this->account()->sum('amount');
}
I don't know how to use Has Many Through.
Or how to solve this situation
I don't need an account at the front but I need sum of amounts
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我这样做了,
之后写入帐户总和 -> 金额
添加了发票列,以在添加 AccountObserver
控制器
视图
I did so
added invoice column to write sum of account->amounts
after than added AccountObserver
Controller
View
这将创建一个 SQL 查询。如果你在 foreach 循环中调用它,它将执行 N 次查询。
您可以急切地加载总和。
从
Client
模型中删除getInvoiceAttribute
方法This creates a SQL query. If you call it in a foreach loop, it will do N Queries.
You could eager load the sum.
Remove the
getInvoiceAttribute
method from theClient
Model