使用attach()在模型和数据透视模型之间添加关系

时间:2018-07-24 20:47:28

标签: laravel eloquent laravel-5.6

我有一个称为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]:列不   找到:1054'字段列表'中的未知列''(SQL:插入   collection_user_webpage(``,collection_id)个值(1、1))

是否可以创建这种类型的关系?还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

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