在Laravel中,我有一張用戶表和一張聲明表,採用多對多關係。每個通知都給予一組用戶,每個用戶可以將通知標記爲獨立閱讀。中間表(notice_user_map)爲此具有「讀取」列。如何在數據透視表中使用Eloquent'saveMany'?
我正在嘗試創建「標記爲已讀」功能,但無法看到如何通過Eloquent完成此操作。這裏的基本代碼:
$notices = $user->notices()
->where('read', 0)
->get();
foreach ($notices as $notice) {
$notice->pivot->read = 1;
}
$authUser->notices()->saveMany($notices);
所以這個發現所有未讀通知該用戶,並通過他們循環,設置在中間(透視)表中的「讀」屬性。但最後一行給出了錯誤
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::saveMany() must be of the type array, object given
如果我手動創建一個數組,我得到這個錯誤:
Integrity constraint violation: 1062 Duplicate entry '4293672207-2904708423' for key 'notice_user' (SQL: insert into
notice_user_map
(created_at
,notice_id
,updated_at
,user_id
) values (2016-01-06 17:53:39, 4293672207, 2016-01-06 17:53:39, 2904708423))
我無法訪問樞軸就像$authUser->notices()->pivot
無論是。
在數據透視表中批量保存數據的正確方法是什麼?
我得到一個錯誤與此:'完整性約束違規:1052列「的updated_at」在字段列表是不明確的(SQL:更新\'通知\ ''內聯'\'notice_user_map \'在'通知'上。\'id \'=''notice_user_map \'。\'notice_id \'set \'read \'= 1,''updated_at \'= 2016-01 -06 23時49分45秒其中\'notice_user_map \'。\'USER_ID \'= 2904708423和\'notice_user_map \'。\'讀\'= 0)' – DisgruntledGoat
@DisgruntledGoat啊,抱歉。如果您的數據透視表上也有時間戳,那麼您將得到該錯誤。不知道爲什麼Laravel仍然沒有列名稱的前綴,但我用另一個解決方案編輯我的答案。 –