使用 attach() 添加 Model 和 Pivot Model 之间的关系

Using attach() to add relationship between Model and Pivot Model

我有一个名为 UserWebpage 的多对多关系的数据透视模型。

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserWebpage extends Pivot
{
    public function collections(){
        return $this->belongsToMany('App\Collection', 'collection_user_webpage');
    }
}

我还有一个模型叫 Collection

namespace App;

use Illuminate\Database\Eloquent\Model;

class Collection extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function userWebpages(){
        return $this->belongsToMany('App\UserWebpage', 'collection_user_webpage');
    }
}

我正在尝试在 UserWebpage 和 Collection 之间建立多对多关系。根据我发现的这个 SO 问题,我知道这样的事情应该是可能的: Laravel: How to use multiple pivot table relationships

我的问题是:

当我尝试在 UserWebpage 实例和 Collection 实例之间插入关系时,出现以下错误。

插入关系的代码:

App\UserWebpage::where('user_id', $user->id)->take(2)->get()->each(function($user_webpage) use ($user){
    $collection = factory(App\Collection::class)->create(['user_id' => $user_webpage->user_id]);
    $collection->userWebpages()->attach($user_webpage->id);
});

我得到的错误:

Illuminate\Database\QueryException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'field list' (SQL: insert into collection_user_webpage (``, collection_id) values (1, 1))

是否可以建立这种类型的关系?还是我遗漏了什么?

$foreignPivotKey 的默认值在 Pivot 中不起作用,您必须明确指定它:

public function collections(){
    return $this->belongsToMany('App\Collection', 'collection_user_webpage', 'user_webpage_id');
}