更改集合中的数据不会保存

时间:2018-09-06 06:43:16

标签: laravel collections

我正在尝试在此集合中添加食物属性:

   $days = $days->each(function($day) use($orderedDays, $order) {

      $foods = collect($day->foods)->map(function(&$food, $keys) use($day, $orderedDays, $order){

        if(in_array($day['id'], $orderedDays)) {

          $item = OrderItem::where('order_id', $order->id)->where('meal_plan_day_id', $day['id'])->first();

          $qty = $item->qty;
          $food->qty = $qty;
          return $food;

        } else {
          $food->qty = 0;
          return $food;
        }

      });

    });

我的问题是,当我在地图中转储时,$ food-> qty没有保存:

                    "food_name": "test",
                    "final_price": 51000,
                    "max_no_order": 1,
                    "extra_no_price": 51000,
                    "qty" :2

但其中每一个都没有保存

2 个答案:

答案 0 :(得分:1)

如果要修改数据,还必须在$days上使用map函数,并在此函数中返回修改后的$days变量。

$days = $days->map(function ($day) use ($orderedDays, $order) {

    $day->foods = collect($day->foods)->map(function ($food, $keys) use ($day, $orderedDays, $order) {

        if (in_array($day['id'], $orderedDays)) 
        {
            $item = OrderItem::where('order_id', $order->id)->where('meal_plan_day_id', $day['id'])->first();

            $qty = $item->qty;
            $food->qty = $qty;
        } 
        else
        {
            $food->qty = 0;
        }

        return $food;

    });

    return $day;

});

答案 1 :(得分:0)

您必须通过引用分配该数组值。使用“&$变量”。

$days = $days->each(function($day) use($orderedDays, $order) {

  $foods = collect($day->foods)->map(function(&$food, $keys) use($day, $orderedDays, $order){

    if(in_array($day['id'], $orderedDays)) {

      $item = OrderItem::where('order_id', $order->id)->where('meal_plan_day_id', $day['id'])->first();

      $qty = $item->qty;
      $food->qty = $qty;
      return $food;

    } else {
      $food->qty = 0;
      return $food;
    }

  });

});