【发布时间】:2021-06-19 20:36:21
【问题描述】:
我有两张桌子(型号), 带有 id 和 name 的标签和 post_tag 与 post_id 和 tag_id。
我如何从表标签名称中获取但使用表 post_tag post_id。
【问题讨论】:
-
你已经厌倦的代码在哪里?
我有两张桌子(型号), 带有 id 和 name 的标签和 post_tag 与 post_id 和 tag_id。
我如何从表标签名称中获取但使用表 post_tag post_id。
【问题讨论】:
看,你还没有给出任何代码示例。但从你的问题来看,我猜你有两个模型,Tag & Post
因此,您的 post_tag 成为了正确的数据透视表。而且是多对多的关系。
在你的 Tag 模型构建关系中,
public function postTag()
{
return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
}
以同样的方式,在您的 Post 模型中添加类似的关系
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
现在,您的轴心关系已准备就绪。在使用Post 附加标签时,请使用$post->tags()->attach(Tag::find($tag)); // $post = new Post(); $tag is tag_id
要检索所有带有关联标签的帖子,请调用
Post::with('tags')->get();
同样,获取与帖子相关的标签
Tag::with('postTag')->get();
前往 laravel 官网获取多对多关系文档 laravel One To Many Eloquent
【讨论】: