gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:20:49 25 4
gpt4 key购买 nike

如何定义带有额外字段的多对多态关系?

我有三个(或更多,因为它是一个多态关系)表。
tags table: id, nametagged table: id, tag_id, taggable_id, taggable_type, user_idposts table: id, record, timestampsusers 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');
}

然后,当我在 Controller 中尝试此操作时:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);

我没有user_id,因此违反了“完整性约束”:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)). Which is somewhat expected, as I have never had the chance to define or declare the user_id field.



另外,我已经尝试过在标签关系上使用withPivot(),如下所示,但无济于事:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}

最佳答案

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

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

关于Laravel-与额外字段的多对多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30500492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com