猿问

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

我想用一个关系连接两个表。表格得到更新,但没有按预期更新。在一种情况下,我得到了 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

我希望在发送相同的请求时,它什么都不做,因为记录已经存在。


白衣非少年
浏览 176回答 2
2回答

墨色风雨

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

拉莫斯之舞

Sync()将删除表中所有没有在方法输入中的 id,如果您只想向多对多关系添加一个条目。您可以使用该syncWithoutDetaching()方法。foreach ($account['network'] as $key => $network) {    $accountModel->networks()->syncWithoutDetaching($network, ['url' =>     $network['url'], 'network_id' => $network['id']]);}
随时随地看视频慕课网APP
我要回答