Laravel - 与额外字段的多对多变形关系

Cra*_*ode 8 laravel eloquent

如何使用额外字段定义多对多的多态关系?

我有三个(或更多,因为它是多态关系)表.

tags table: id, name

tagged table: id, tag_id, taggable_id, taggable_type, user_id

posts table: id, record, timestamps

users table: id, name, email

user_id上标记表referes到用户表上的id列.在我的Post模型中,我有:

public function tags()
{
    return $this->morphToMany('App\Tag', 'taggable','tagged');
}
Run Code Online (Sandbox Code Playgroud)

在我的Tag模型中,我有:

public function posts()
{
    return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Run Code Online (Sandbox Code Playgroud)

然后当我在我的控制器中尝试这个时:

$tag = new \App\Tag(
array(
    'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
Run Code Online (Sandbox Code Playgroud)

由于没有user_id,我收到了Integrity Constraint Violation:

SQLSTATE [23000]:完整性约束违规:1452不能添加或更新子行,外键约束失败(hb.tagged,约束tagged_user_id_foreign外键(user_id)参考users(id))(SQL:插入tagged(tag_id,taggable_id,taggable_type)值(26,2,应用程序\资源)).这是有点预期的,因为我从未有机会定义或声明user_id字段.

此外,我已经尝试使用标签关系上的Pivot()如下,无济于事:

public function tags()
{
    return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*zyk 9

喜欢在评论中:withPivot与此无关saving/creating.如果要在何时传递其他数据透视数据saving,请执行以下操作:

$post->tags()->save($tag, ['user_id' => $userId]);
Run Code Online (Sandbox Code Playgroud)