簡體   English   中英

從Laravel中的數據透視表獲取數據

[英]getting data from a pivot table in laravel

我有3個表:post,tag,tag_post。

我將post_id保存在post中,將tag_id保存在標簽中,並將它們都保存在tag_post中。

如何顯示每個帖子的標簽? 如何從tag_post表中選擇數據?

這是我的Post模型:

  public function tag()
         {
           return  $this->belongsToMany('Tag','tag_post');
         }

這是我的Tag模型:

 public function post()
         {
           return  $this->belongsToMany('Post','tag_post');
         }

這是我的控制器:

$posts=Post::orderBy('id','DESC')->paginate(5);
///but I dont know how can i show each post's tags under it 

謝謝你的時間。

如果需要從每個post獲取tags ,則需要一個foreach循環。

foreach ($posts as $post)
{
    var_dump($post->tags); // your individual post's tags will be here
}

另外,盡管我不喜歡戳我的鼻子,但如果遵循框架本身的約定會更好。 (即在多對多關系中使用復數形式)

郵政模型

public function tags() // <-- note the plurals
{
    $this->belongsToMany('Tag', 'tag_post');
}

標簽模型

public function posts() // <-- note the plurals
{
    $this->belongsToMany('Post', 'tag_post');
}

如果您需要從tag_post表中獲取數據,請查閱有關使用數據透視表的文檔。

http://laravel.com/docs/eloquent#working-with-pivot-tables

這里有幾件事(我會保持簡單,因此沒有orderBy或其他任何東西,我還假設您將關系重命名為復數: tags()posts()以便於閱讀和使用)

$posts = Post::paginate(5); // returns a Collection of Post models, 1 db query

foreach ($posts as $post) {
  $post->tags; // Collection of Tag models, fetched from db for each $post
}

這意味着5 + 1個查詢。 當然,它並不能完全擴展,因此我們需要http://laravel.com/docs/eloquent#eager-loading

這導致我們:

$posts = Post::with('tags')->paginate(5); // returns a Collection of Post models
// runs 1 query for posts and 1 query for all the tags

foreach ($posts as $post) {
  $post->tags; // Collection of Tag models, no more db queries
}

因此,要列出所有標簽,您可以執行以下操作:

@foreach ($posts as $post)
   <tr>
     <td>{{ $post->title }}</td>
     <td>
       @foreach ($post->tags as $tag)
          {{ $tag->name }}   // or whatever it is that you want to print of the tag
       @endforeach
     </td>
   </tr>
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM