php - Laravel 在查询中使用函数
问题描述
在这样的控制器data
中db
,我想将整个传递$request
给该控制器中的另一个函数,以price
使其根据以下许多事物计算价格$request
:
$user = Auth::user();
$query = Post::query();
$query
->where('province', '=', $user->province)
->where('city', '=', $user->city);
$customers = $query->get();
$customers['calculator'] = $this->calculator($request); // call function
我的问题是它像这样返回:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
},
"calculator": {
"price": 1
}
}
但我需要对每个数据使用该函数,结果应该是这样的:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
"calculator": {
"price": 1
}
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
"calculator": {
"price": 1
}
}
}
解决方案
您想要的是为集合中的calculator
每个项目设置一个键$customers
。所以你需要循环它:
foreach ($customers as $customer) {
$customer->calculator = $this->calculator($request);
}
请注意,由于$customer
是 a Model
,您应该将计算器设置为属性。在内部,它将被设置为属性数组。
推荐阅读
- javascript - 我想循环提示并将每个循环保存在数组中
- office-js - Excel 加载项:XML 文本换行
- python - Python 将 windowsPath 添加到 sys.path
- tkinter - GUI 及其小部件可以适应任何屏幕分辨率的方法是什么?
- python - Python TypeError:对象不可迭代
- flutter - 如何访问 InheritedWidget 的 InheritedWidget?
- python - 在 QGIS 上使用 python 控制台进行栅格计算
- jpa - JPA 和继承 - 使用子类处理自引用
- amazon-web-services - ALB - 不使用 HTTP 80 时的 EC2 504 网关超时
- c++ - QSignalMapper 字符串问题