Foreach并从其他表中获取标签和类别

时间:2014-04-05 14:26:03

标签: database laravel foreach tags

我很难想到好的头衔,但我希望这可以解释。

帖子表

+----+---------+-----------------+
| id |  title  |      text       |
+----+---------+-----------------+
|  1 | Title 1 | This is example |
|  2 | Title 2 | This is example |
|  3 | Title 3 | This is example |
+----+---------+-----------------+

标签表

+----+--------+
| id |  tag   |
+----+--------+
|  1 | jQuery |
|  2 | PHP    |
|  3 | Stack  |
+----+--------+

类别表

+----+------------+
| id |  category  |
+----+------------+
|  1 | Category 1 |
|  2 | Category 2 |
|  3 | Category 3 |
+----+------------+

帖子标签关系表(与类别相同)

+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      1 |
|       1 |      2 |
|       2 |      3 |
+---------+--------+

这是我希望在我的观点中看到的结果:

+---------+------------------+--------------------+------------+
|  Title  |       Text       |        Tags        | Categories |
+---------+------------------+--------------------+------------+
| Title 1 | This is example  | jQuery, PHP        | Category 2 |
| Title 2 | This is example  | Stack              | Category 1 |
| Title 3 | This is example  | jQuery, PHP, Stack | Category 1 |
+---------+------------------+--------------------+------------+

在我的控制器中我有

public function index()
{
  $posts = Posts::orderBy('title', 'ASC')->get();

  return View::make('posts', array(
    'posts' => $posts)
  );
}

在我看来,我可以使用foreach循环列出所有帖子

@foreach ($posts as $post)
  Title: {{ $post->title }}
  Text: {{ $post->text }}
  Tags: ?
  Categories: ?
@endforeach

问题是什么是获取foreach循环中每个帖子的标签和类别的最佳方法?

1 个答案:

答案 0 :(得分:0)

Shakil的提示就在当场,我找到了我想要的东西。我很惊讶它很容易实现。这是我做的:

帖子 - 模型

class Posts extends Eloquent 
{
   protected $table = 'posts';

   public function tags()
   {
     return $this->belongsToMany('Tags', 'post_tags', 'post_id', 'tag_id');
   }

   public function category()
   {
     return $this->belongsToMany('Category', 'post_categories', 'post_id', 'category_id');
   }
}

查看

@foreach ($posts as $post)
  Title: {{ $post->title }}
  Text: {{ $post->text }}

  Tags: 
    @foreach ($post->tags as $tag)
      {{ $tag }}
    @endforeach

  Categories: 
    @foreach ($post->categories as $category)
     {{ $category }}
    @endforeach

@endforeach

感谢大家的帮助!