首页 > 解决方案 > Laravel 在查询中使用函数

问题描述

在这样的控制器datadb,我想将整个传递$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
    }
  }
}

标签: phplaravel

解决方案


您想要的是为集合中的calculator每个项目设置一个键$customers。所以你需要循环它:

foreach ($customers as $customer) {
    $customer->calculator = $this->calculator($request);
}

请注意,由于$customer是 a Model,您应该将计算器设置为属性。在内部,它将被设置为属性数组。


推荐阅读