我想用一個關(guān)系連接兩個表。表格得到更新,但沒有按預(yù)期更新。在一種情況下,我得到了 2 次相同的記錄,在另一種方法中,我只得到了一條沒有數(shù)據(jù)的記錄。使用 attach 方法,我得到兩次相同的記錄,每次我發(fā)送相同的請求時,它都會創(chuàng)建與以前相同的記錄。使用同步方法,它只添加循環(huán)中的最后一條記錄。我認為同步是要走的路,因為它在發(fā)送相同的請求時不會創(chuàng)建新記錄。 // Network Model public function accounts() { return $this->belongsToMany('App\Account'); } // Account Model public function networks() { return $this->belongsToMany('App\Models\Network')- >withPivot('url'); } // Updateprofile function in accounts controller $accounts = $request->get('accounts'); foreach ($accounts as $key => $account) { $accountModel = Account::where("id", "=", $account['id'])- >first(); /* Some other fields that get updated ... */ $networks = Network::find(Helper::getValueOrDefault(AuthConst::NETWORK, $account, [])); foreach ($account['network'] as $key => $network) { $accountModel->networks()->sync($network, ['url' => $network['url'], 'network_id' => $network['id']]); } $accountModel->save(); }數(shù)據(jù)庫結(jié)構(gòu)Accounts TableID | And some metafieldsNetwork TableID | Name | slugAccount_network relation TableID | network_id | account_id | url該請求給出了一個名為network的數(shù)組,其中包含一個或多個對象array(2) { [0]=> array(2) { ["id"]=> int(3) ["url"]=> string(19) "http://facebook.com" } [1]=> array(2) { ["id"]=> int(2) ["url"]=> string(18) "http://youtube.com" }}我希望這會附加到正確的帳戶,并將兩條記錄添加到Account_network表中。ID | network_id | account_id | url 1 | 3 | 1| http://facebook.com2 | 2 | 1| http://youtube.com我希望在發(fā)送相同的請求時,它什么都不做,因為記錄已經(jīng)存在。
2 回答

墨色風(fēng)雨
TA貢獻1853條經(jīng)驗 獲得超6個贊
附加僅向數(shù)據(jù)透視表添加新記錄。Sync 接受一個 id 或一個 id 數(shù)組,刪除所有記錄并只插入那些出現(xiàn)在同步方法中的記錄。它接受第二個參數(shù)作為 bool,它允許您防止這種刪除,或者您可以使用 syncWithoutDetaching 方法。所以你不需要同步的 foreach,因為它不會像你預(yù)期的那樣工作。

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超10個贊
Sync()將刪除表中所有沒有在方法輸入中的 id,如果您只想向多對多關(guān)系添加一個條目。您可以使用該syncWithoutDetaching()方法。
foreach ($account['network'] as $key => $network) {
$accountModel->networks()->syncWithoutDetaching($network, ['url' =>
$network['url'], 'network_id' => $network['id']]);
}
- 2 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報
0/150
提交
取消