How to encode an array of data and save to a pivot table laravel

做~自己de王妃 提交于 2019-12-23 04:22:11

问题


All I want here is to be able to save all the ID's of services into the pivot table associated with the given keywords/tags but at the moment all it does is that it takes the last ID of the created object and saves into the pivot table with different keywords. let's say for example I enter [id1 => service1, id2 => service2] and [id1 = > keyword1, id2 => keyword2, id3 => keyword3] instead of it saving only id2 of service2 and all the keywords I want it to save all the Ids of all of the services and the keywords. I hope it makes sense

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']]]);
  }

This is something I would expect but it is tricky because a single or 2 services for example can have multiple keywords. NOTE: I had manually changed these values in the database

These are the results from a dd($params)

Based on the dd($params).attached is the result,only

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

was saved in the pivot table and got assigned all the keywords


回答1:


Please correct me if this is a good approach, I managed to solve this by having an inner loop.

    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']]]);
    }
}



来源:https://stackoverflow.com/questions/52140515/how-to-encode-an-array-of-data-and-save-to-a-pivot-table-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!