Laravel 4 /显示带有类别标题的帖子(关系pb)

时间:2013-12-04 00:52:07

标签: php laravel eloquent has-and-belongs-to-many

这就是我要在课程索引页面上显示的内容。

  • 第1类 - 课程1 - 课程2 - 课程3
  • 第2类 - 课程4 - 课程5 - 课程6

课程表

Schema::create('courses', function($table) {      
    $table->engine = 'InnoDB';
    $table->increments('id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->string('title');
    $table->string('slug');
    $table->integer('category_id')->unsigned();
    $table->text('content');
    $table->string('meta_title');
    $table->string('meta_description');
    $table->string('meta_keywords');
   $table->timestamps();
});

类别表

Schema::create('categories', function($table) {   
    $table->engine = 'InnoDB';
    $table->increments('id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->string('title');
    $table->string('slug');
    $table->text('description');
    $table->timestamps();
});

课程模型

public function category()
{
    return $this->hasOne('Category', 'id');
}

类别模型

public function courses() {
    return $this->hasMany('Course', 'id');
}

课程控制器

public function getIndex()
{
    $categories = Category::all();
    $courses = Course::all();
    return View::make('site/eap/course/index', compact('categories', 'courses'));
}

课程索引视图

@foreach($categories as $category)
<h3>{{ $category->title }}</h3>
    @foreach($courses as $course)
    <h4><a href="{{{ $course->url() }}}">{{ $course->title }}</a></h4>
    <p>{{ $course->content }}</p>
    @endforeach
@endforeach

当我只想要相应类别的课程时,这显然会返回每个类别下的所有课程。

我尝试了一切,但我想我错过了显而易见的事情。我应该在哪里做循环,我该在哪里做?在控制器中,在视图中,两者中?我们如何将它们粘合在一起?

1 个答案:

答案 0 :(得分:2)

您的课程没有一个分类,属于一个:

public function category ()
{
    return $this->belongsTo('Category');
}

然后在你的控制器中:

$categories = Category::with('courses')->get();

并在您看来:

@foreach($categories as $category)

    <h3>{{ $category->title }}</h3>

    @foreach($category->courses as $course)

        <h4><a href="{{ $course->url() }}">{{ $course->title }}</a></h4>
        <p>{{ $course->content }}</p>

    @endforeach

@endforeach