![](/img/trans.png)
[英]How I can get distinct records from laravel table using elequent model?
[英]How I can get data from table laravel model
我有两个表(模型),带有 id 和 name 的标签和带有 post_id 和 tag_id 的 post_tag。
我如何从表标签名称中获取但使用表 post_tag post_id。
看,你还没有给出任何代码示例。 但从你的问题来看,我猜你有两个 model 命名, Tag
和Post
因此,您的 post_tag 正确地变成了 pivot 表。 而且是多对多的关系。
在您的Tag
model 中建立关系,例如,
public function postTag()
{
return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
}
同样,在您的Post
model 中添加如下关系
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
现在,您的 pivot 关系已准备就绪。 在使用Post
附加标签时,使用$post->tags()->attach(Tag::find($tag)); // $post = new Post(); $tag is tag_id
$post->tags()->attach(Tag::find($tag)); // $post = new Post(); $tag is tag_id
要检索所有带有关联标签的帖子,请调用
Post::with('tags')->get();
同样,获取与帖子关联的标签
Tag::with('postTag')->get();
前往 laravel 官方网站获取多对多关系文档laravel 一对多 Eloquent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.