[英]Laravel, sync data with Pivot
Laravel 5.3,我有這兩個模型:
用戶:
public function newFunctions()
{
return $this
->belongsToMany('App\NewFunctions', 'user_newfunctions')
->withPivot(['function_count', 'days_count']);
}
新功能:
public function users()
{
return $this
->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')
->withPivot(['function_count', 'days_count']);
}
我現在如何將新數據保存到用戶,如下:
$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->save();
但是現在我必須更新數據透視表的一些值。 數據透視表是這樣的:
user_id | new_functions_id | function_count | days_count
---------------------------------------------------------
814 | 1 | 5 |2019-07-19 12:26:19
814 | 3 | 7 |2019-07-19 12:26:19
每個user_id
有超過 1 行。 我試圖使用:
$user
->newFunctions()
->sync([
'days_count' => $test_date,
'function_count' => $test_int_number
]);
但我收到如下錯誤:
非法偏移類型
因為正在嘗試更新:
array(
'records' => array(
'days_count' => object(Carbon), 'function_count' => '66'),
'results' => array(),
'id' => object(Carbon),
'attributes' => array()
)
)
in BelongsToMany.php
所以:
sync
來更新“function_count”和“days_count”? 他們來自請求。 ->sync()
不是這樣使用的; 它用於attach()
和detach()
相關的new_function_ids
直到只有sync()
中的ids
出現。 您可能正在尋找updateExistingPivot()
->sync()
一個例子是使用數組:
$user->newFunctions()->sync([
"new_function_id" => 1,
"function_count" => 6,
"days_count" => "2019-07-08 12:00:00",
]);
這將刪除new_function_id
為3
的記錄,並更新new_function_id
為1
的值。
要為1
或3
new_function_id
更新function_count
和days_count
,請使用->updateExistingPivot()
(傳遞要更新的id
作為第一個參數):
$user
->newFunctions()
->updateExistingPivot("1", [
"function_count" => 6,
"days_count" = "2019-07-08 12:00:00"
]);
// or $user->newFunctions()->updateExistingPivot("3", ...);
這將更新new_function_id
為1
的數據透視表,同時保留new_function_id
為3
的行。
編輯:如果您要更新數據透視表中的所有現有記錄,則需要在循環中執行此操作,對單個數組中的所有當前記錄調用同步,或運行手動查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.