简体   繁体   中英

getting data from a pivot table in laravel

I have 3 tables :post , tag , tag_post.

I save post_id in post / tag_id in tag / and both of them in tag_post.

how can I show every post's tags ? how can I select data from tag_post table?

it's my Post model :

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

and it's my Tag model :

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

and it's my controller :

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

thanks for your time.

If you need to get the tags from each post you need a foreach loop.

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

Also, as much as I don't like to poke my nose around, it would be better if you follow the conventions in the framework itself. (ie use plurals form in many-to-many relationship)

Post Model

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

Tag Model

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

If you need to get data from the tag_post table, check out the documentation on working with pivot table.

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

A few things here (I will keep it simple so no orderBy or anything else, also I assume you rename relations to plural: tags() and posts() to make it easier to read and work with):

$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
}

This means 5+1 queries. It doesn't scale at all of course, so we need http://laravel.com/docs/eloquent#eager-loading

Which leads us to:

$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
}

So to list all the tags you could do this:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM