[英]Laravel 4 / Displaying posts with a category header (relationships pb)
这就是我想在课程索引页面上显示的内容。
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
当我只想要相应类别的课程时,这显然会返回每个类别下的所有课程。
我尝试了所有可能的方法,但我想我还是没能做到。 我应该在哪里做循环,在哪里做? 在控制器中,在视图中,在两者中? 我们如何将它们粘合在一起?
你当然没有一个categoy,它属于一个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.