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

时间:2015-05-28 07:57:15

标签: 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引用列id上的users表。 在我的Post模型中,我有:

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

在我的Tag模型中我有:

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

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

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

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

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(hbtagged,CONSTRAINT tagged_user_id_foreign FOREIGN KEY({{ 1}})REFERENCES user_idusers))(SQL:插入idtaggedtag_idtaggable_id)值(26 ,2,App \ Resource))。   这是有点预期的,因为我从未有机会定义或声明user_id字段。

另外,我在标签关系上尝试使用了Pivot(),如下所示,无济于事:

taggable_type

1 个答案:

答案 0 :(得分:8)

与评论中一样:withPivotsaving/creating无关。如果您想在saving时传递其他数据透视数据,请执行以下操作:

$post->tags()->save($tag, ['user_id' => $userId]);
相关问题