如何编码数据数组并保存到数据透视表中

时间:2018-09-02 19:49:33

标签: php laravel eloquent pivot-table

我在这里想要做的是能够将所有服务的ID保存到与给定关键字/标签相关联的数据透视表中,但目前所做的只是获取已创建对象的最后一个ID并保存到具有不同关键字的数据透视表。假设我输入[id1 => service1,id2 => service2]和[id1 => keyword1,id2 => keyword2,id3 => keyword3],而不是仅保存service2的id2和我想要的所有关键字保存所有服务和关键字的所有ID。我希望这是有道理的

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

    foreach($params['keywords'] as $keyword){
      $cleaned_keyword = self::cleanKeywords($keyword); 
      $newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
      $newKeyword->keyword = $cleaned_keyword;
      $newKeyword->save();
      $service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
  }

none

这是我所期望的,但是很棘手,因为例如一个或两个服务可以有多个关键字。注意:我已经手动更改了数据库中的这些值 enter image description here

这些是dd($ params)的结果

enter image description here

基于dd($ params).attached是结果,仅

"service" => array:2[
1 => "Mobile development"
]

已保存在数据透视表中并分配了所有关键字

enter image description here

1 个答案:

答案 0 :(得分:0)

如果这是一个好方法,请纠正我,我设法通过内部循环解决了这个问题。

    foreach($params['service'] as $key => $value) {
    $service = Service::firstOrNew(['service' => $value, 'price' => $params['price'][$key], 'business_id' => $params['business_id']]);
    $service->service = $value;
    $service->price = $params['price'][$key];
    $service->business_id = $params['business_id'];
    $service->save();
    foreach($params['keywords'] as $keyword) {
        $cleaned_keyword = self::cleanKeywords($keyword);
        $newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
        $newKeyword->keyword = $cleaned_keyword;
        $newKeyword->save();
        $service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
    }
}

enter image description here