Home > database >  Sync multiple IDs in laravel
Sync multiple IDs in laravel

Time:11-10

I'm doing a dental function, I'm looking to sync data in a many-to-many relationship. I have the following:

tooth
- id
- name

cost 
- id
- name

cost_tooth
- id
- tooth_id
- cost_id
- row_number

This is the data I got from input checkbox tooth_id, I have an array like this

[
 0 => [
    1 =>  ["row_number" => 1]
    2 =>  ["row_number" => 1]
    3 =>  ["row_number" => 1]
    4 =>  ["row_number" => 1]
  ]
 1 => [
   1 =>  ["row_number" => 2]
   2 =>  ["row_number" => 2]
   3 =>  ["row_number" => 2]
   4 =>  ["row_number" => 2]
 ]
]

my code

foreach ($output as $key => $value) {
  $cost_id->tooths()->sync($value);
}

I only get the last data but not all the data.

enter image description here

I know attach method can solve for me but I want to try with sync method

CodePudding user response:

Because you use sync in loop

foreach ($output as $key => $value) {
  $cost_id->tooths()->syncWithoutDetaching($value);
}

if you want update version

$sync_value = []
foreach ($output as $key => $value) {
 $sync_value[] = $value; 
}
$cost_id->tooths()->sync($sync_value);

if you want store version

$attach_value = []
foreach ($output as $key => $value) {
 $attach_value[] = $value; 
}
$cost_id->tooths()->attach($attach_value);

CodePudding user response:

I solved my problem, here is my code

$output = [
 0 => [
    1 =>  ["row_number" => 1]
    2 =>  ["row_number" => 1]
    3 =>  ["row_number" => 1]
    4 =>  ["row_number" => 1]
  ]
 1 => [
   1 =>  ["row_number" => 2]
   2 =>  ["row_number" => 2]
   3 =>  ["row_number" => 2]
   4 =>  ["row_number" => 2]
 ]
];

foreach ($output as $key => $value) {
  $cost_id->tooths()->sync($value);
}

Edit

$output = [
  0 => [
    "tooth_id" => "1"
    "row_number" => 1
  ]
  1 => [
    "tooth_id" => "2"
    "row_number" => 1
  ]
  2 => [
    "tooth_id" => "3"
    "row_number" => 1
  ]
  3 => [
    "tooth_id" => "4"
    "row_number" => 1
  ]
  4 => [
    "tooth_id" => "5"
    "row_number" => 1
  ]
]

foreach ($output as $key => $value) {
  $cost_id->tooths()->sync($value);
}

But I still have a problem, it's updating

  • Related