我正在做牙科功能,我希望在many-to-many關系中同步資料。我有以下內容:
tooth
- id
- name
cost
- id
- name
cost_tooth
- id
- tooth_id
- cost_id
- row_number
這是我從輸入復選框得到的資料tooth_id,我有一個這樣的陣列
[
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);
}
我只得到最后的資料,但不是所有的資料。
在此處輸入影像描述
我知道attach方法可以解決我,但我想嘗試sync方法
uj5u.com熱心網友回復:
因為你在回圈中使用同步
foreach ($output as $key => $value) {
$cost_id->tooths()->syncWithoutDetaching($value);
}
如果你想更新版本
$sync_value = []
foreach ($output as $key => $value) {
$sync_value[] = $value;
}
$cost_id->tooths()->sync($sync_value);
如果你想要商店版本
$attach_value = []
foreach ($output as $key => $value) {
$attach_value[] = $value;
}
$cost_id->tooths()->attach($attach_value);
uj5u.com熱心網友回復:
我解決了我的問題,這是我的代碼
$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);
}
編輯
$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);
}
但是我還是有問題,正在更新中
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/531419.html
