简体   繁体   中英

Laravel - restructuring array for easy sync of many-to-many with additional pivot data

I have created what feels like a clunky solution to restructuring a data array in order to pass it to a sync() to update a many-to-many relationship with additional data in the pivot table and wondered if anyone could suggest a simpler approach.

I have an array coming from a request, here's a relevant extract:

"papers" => [
    0 => [
      "id" => 2
      "code" => "123-321-888"
      "name" => "Pop out"
      "pivot" => [
        "job_id" => 46
        "paper_id" => 2
        "qty_required" => 500
      ]
    ]
    1 => [
      "id" => 1
      "code" => "444-666-999"
      "name" => "Premium pro"
      "pivot" => [
        "job_id" => 46
        "paper_id" => 1
        "qty_required" => 1000
      ]
    ]
  ]

In order to do an easy sync of a many-to-many relationship with extra pivot data one needs to restructure that to:

[
 paper[id] => [ 
    'qty_required' => paper[pivot][qty_required] 
    ]
]

Which for the above example would be:

[
  2 => [
    "qty_required" => "500"
  ]
  1 => [
    "qty_required" => "1000"
  ]
]

I'm currently doing a 2-step process to achieve this as follows:

$paperUpdate = Arr::pluck($request->input('papers'), 'pivot.qty_required', 'id');
//output: [  2 => 500,  1 => 1000]

foreach ($paperUpdate as $key => $value) {
    $paperSync[$key]['qty_required'] = $value;
}

//output: [ 2 => [ "qty_required" => "500" ],  1 => [ "qty_required" => "1000" ]

$job->papers()->sync($paperSync);

Is there an easier approach?

Your approach seems fine to me. If you want to nit pick, you could do one less iteration using:

$sync = array_reduce($request->input('papers'), function ($sync, $paper) {
    $id = $paper['id'];
    $sync[$id] = [ 'qty_required' => $paper['pivot']['qty_required'] ];

    return $sync;
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM