我想用一个关系连接两个表。表格得到更新,但没有按预期更新。在一种情况下,我得到了 2 次相同的记录,在另一种方法中,我只得到了一条没有数据的记录。
使用 attach 方法,我得到两次相同的记录,每次我发送相同的请求时,它都会创建与以前相同的记录。
使用同步方法,它只添加循环中的最后一条记录。我认为同步是要走的路,因为它在发送相同的请求时不会创建新记录。
// 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();
}
数据库结构
Accounts Table
ID | And some metafields
Network Table
ID | Name | slug
Account_network relation Table
ID | network_id | account_id | url
该请求给出了一个名为network的数组,其中包含一个或多个对象
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.com
2 | 2 | 1| http://youtube.com
我希望在发送相同的请求时,它什么都不做,因为记录已经存在。
墨色风雨
拉莫斯之舞