【问题标题】:getting data from a pivot table in laravel从 laravel 中的数据透视表中获取数据
【发布时间】:2014-07-05 08:37:39
【问题描述】:

我有 3 个表:post、tag、tag_post。

我将 post_id 保存在 post / tag_id 中 tag / 并将它们都保存在 tag_post 中。

如何显示每个帖子的标签?如何从 tag_post 表中选择数据?

这是我的帖子模型:

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

这是我的标签模型:

 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 

感谢您的宝贵时间。

【问题讨论】:

    标签: php laravel eloquent pivot-table


    【解决方案1】:

    这里有几件事(我会保持简单,所以没有 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
    

    【讨论】:

      【解决方案2】:

      如果您需要从每个 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

      【讨论】:

      • 你可以试试这个$p-&gt;tag()-&gt;get('name')
      猜你喜欢
      • 2019-07-25
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多