保存到数据库时雄辩地复制行-laravel

时间:2018-08-30 07:05:19

标签: php laravel eloquent

当我将数据保存到数据库时,即使数组包含一个索引位置,行也会重复出现此问题。我在这里想念东西吗?

 foreach($params['service'] as $key => $value){
    $data['name'] = $value;
    $data['price'] = $params['price'][$key];  
    $data['business_id'] = $params['business_id'];
    $service = new  Service($data);
    $service->save();
}

$ params的数据

array:5 [▼
  "business_id" => "1"
  "service" => array:1 [▼
    0 => "web development"
  ]
  "price" => array:1 [▼
    0 => "R4500"
  ]
  "submit" => null
]

这些是重复项

1   web development     R4500   1   2018-08-30 07:24:34     2018-08-30 07:24:34
2   web development     R4500   1   2018-08-30 07:24:34     2018-08-30 07:24:34

不幸的是,@ Rathod提供的答案也会产生重复项,但是我注意到,当我向数组中添加多个数据(如下所示)时,它会保存没有重复项。

array:5 [▼
  "business_id" => "1"
  "user_id" => "1"
  "service" => array:3 [▼
    0 => "web development"
    1 => "mobile development"
    2 => "internet marketing"
  ]
  "price" => array:3 [▼
    0 => "R4500"
    1 => "R8900"
    2 => "R5600"
  ]
  "submit" => null
]

这是完整功能

 public function createService(array $params) : Service
{
  // dd($params);
    try {
      foreach($params['service'] as $key => $value){
        $service = new Service();
        $service->service = $value;
        $service->price = $params['price'][$key];
        $service->business_id = $params['business_id'];
        $service->save();
    }
      return $service;

    } catch (QueryException $e) {
        throw new CreateServiceInvalidArgumentException($e->getMessage(), 500, $e);
    }

  }

2 个答案:

答案 0 :(得分:0)

尝试以下简单方法:

foreach($params['service'] as $key => $value){
    $service = new Service();
    $service->name = $value;
    $service->price = $params['price'][$key];
    $service->business_id = $params['business_id'];
    $service->save();
}

我希望它能正常工作。

答案 1 :(得分:0)

那一刻我想愚弄自己...我只是注意到我是通过ajax发送相同的数据的。.我一定忘了我这样做了。非常感谢大家花时间看一下这对我来说。