Laravel按类别获得帖子

时间:2016-11-20 20:39:37

标签: laravel laravel-5 laravel-5.2

我试图弄清楚如何使用Laravel Eloquent 5.3来获取某个类别的所有帖子。

我有三张桌子..

**Posts**
id | title | text

**Term_relationships**
term_id | post_id

**Terms**
id | name

雄辩的模特

class Term extends Model
    {
    public function posts()
    {
         return $this->belongsToMany('App\Post', 'term_relationship');
    }
}


class Post extends Model
{
    public function terms()
    {
        return $this->belongsToMany('App\Term', 'term_relationship');
    }

}

class Term_relationship extends Model
{

}

我已尝试过例如

Term::where('name', $category)->posts->get();

1 个答案:

答案 0 :(得分:0)

易,

如果您想要带有条款的帖子,请执行此操作

$data = App\Post::with('terms')->get();
您认为

@foreach($data as $post) // will loop over posts and show title
<div>{{$post->title }} </div>
 @foreach($post->terms as $term)
  <div> {{ $term->title }} </div>  // will loop and echo all terms for current post
 @endforeach
@endforeach

如果您想要帖子条款,请执行此操作

$data = App\Term::with('posts')->where('name', $category)->get();
您视图中的

@foreach($data as $term) // will loop over terms and show title
<div>{{$term->title }} </div>
 @foreach($term->posts as $term)
  <div> {{ $post->title }} </div>  // will loop and show all posts in each term
 @endforeach
@endforeach

我觉得秒的方式更适合你的需要因为在第一个例子中你将需要使用wherehas和一个闭包