![](/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.