枢纽分析表集合在同步后未更新

时间:2019-05-30 13:11:52

标签: eloquent many-to-many pivot-table laravel-5.8

我正在用Laravel 5.8 / MySQL重新实现在线日记的代码。我有一个用户表和一个文件表,它们具有多对多关系。我正在使用jQuery / Ajax来修改给定论文的作者列表,实质上是使用sync()来加载更新的作者列表。数据透视表包括一个整数列,用于标识该作者在作者列表中的位置。就可以正确更新数据库而言,我的代码可以正常工作,只是作者集合在sync()之后不会更新。

我通过创建与数据库的新连接来解决此问题,但我认为应该有一种更有效的方法。

模型的相关部分为:

纸张型号

    public function authorCollection()
    {
        return $this->belongsToMany('App\Models\User', 'paperauthors', 'paper_id', 'author_id')->withPivot('notes','authorNum');
    }

用户模型

    public function papers()
    {
        return $this->belongsToMany('App\Models\Paper', 'paperauthors', 'author_id', 'paper_id')->withPivot('notes','authorNum');
    }

用于更新作者列表的代码为

    $sync = array();
    // set up array for the sync operation, $authors is derived from the Ajax POST request
    foreach($authors as $auth) {
         $sync[$auth->id] = ['authorNum'=>intval($auth->authorNum)];
    }
    $paper->authorCollection()->sync($sync);
    $paper->save();
    // $paper->authorCollection still has the old data unless I add the following line
    $paper = Paper::where('id',$request->id)->first();

我希望该集合自动包含更新后的数据-是否可以使用功能来更新它,还是必须重新创建连接?

0 个答案:

没有答案