Php Laravel在查询中的使用函数
在controller getPhp Laravel在查询中的使用函数,php,laravel,Php,Laravel,在controller getdatafromdb中,我希望将整个$request传递给该控制器中的另一个函数,以获取价格它根据$request中的许多内容计算价格: $user = Auth::user(); $query = Post::query(); $query ->where('province', '=', $user->province) ->where('city', '=', $user->city); $customers = $query-&g
data
fromdb
中,我希望将整个$request
传递给该控制器中的另一个函数,以获取价格
它根据$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
}
}
}
但我需要对每个数据使用该函数,结果应该是这样的:
{
"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
}
}
}
您需要的是为
$customers
集合中的每个项目设置一个计算器
键。因此,您需要在其上循环:
foreach ($customers as $customer) {
$customer->calculator = $this->calculator($request);
}
请注意,由于
$customer
是模型
,因此应将计算器设置为属性。在内部,它将被设置为属性数组。如果您想将计算器
分配给每个客户
,则需要使用循环。