为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Laravel 中以正确的方式附加关系

如何在 Laravel 中以正确的方式附加关系

PHP
白衣非少年 2022-01-02 16:25:13
我想用一个关系连接两个表。表格得到更新,但没有按预期更新。在一种情况下,我得到了 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 TableID | And some metafieldsNetwork TableID | Name | slugAccount_network relation TableID | 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.com2 | 2 | 1| http://youtube.com我希望在发送相同的请求时,它什么都不做,因为记录已经存在。
查看完整描述

2 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

附加仅向数据透视表添加新记录。Sync 接受一个 id 或一个 id 数组,删除所有记录并只插入那些出现在同步方法中的记录。它接受第二个参数作为 bool,它允许您防止这种删除,或者您可以使用 syncWithoutDetaching 方法。所以你不需要同步的 foreach,因为它不会像你预期的那样工作。


查看完整回答
反对 回复 2022-01-02
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

Sync()将删除表中所有没有在方法输入中的 id,如果您只想向多对多关系添加一个条目。您可以使用该syncWithoutDetaching()方法。


foreach ($account['network'] as $key => $network) {

    $accountModel->networks()->syncWithoutDetaching($network, ['url' => 

    $network['url'], 'network_id' => $network['id']]);

}


查看完整回答
反对 回复 2022-01-02
  • 2 回答
  • 0 关注
  • 175 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号