这就是我要在课程索引页面上显示的内容。
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
当我只想要相应类别的课程时,这显然会返回每个类别下的所有课程。
我尝试了一切,但我想我错过了显而易见的事情。我应该在哪里做循环,我该在哪里做?在控制器中,在视图中,两者中?我们如何将它们粘合在一起?
答案 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