简体   繁体   English

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

[英]Laravel 4 / Displaying posts with a category header (relationships pb)

This is what I'd like to display on a course index page. 这就是我想在课程索引页面上显示的内容。

  • Category 1 -- Course 1 -- Course 2 -- Course 3 类别1-课程1-课程2-课程3
  • Category 2 -- Course 4 -- Course 5 -- Course 6 类别2-课程4-课程5-课程6

Course Table 课程表

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();
});

Category Table 分类表

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();
});

Course Model 课程模式

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

Category Model 分类模型

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

Course Controller 课程负责人

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

Course Index View 课程索引视图

@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

This obviously returns all the courses under each category when I only want the courses of the corresponding category. 当我只想要相应类别的课程时,这显然会返回每个类别下的所有课程。

I tried everything possible but I think I'm missing the obvious. 我尝试了所有可能的方法,但我想我还是没能做到。 Where am I supposed to do the loop and where do I do it? 我应该在哪里做循环,在哪里做? In the controller, in the view, in both? 在控制器中,在视图中,在两者中? How do we glue this together? 我们如何将它们粘合在一起?

Your course doesn't have a categoy, it belongs to one: 你当然没有一个categoy,它属于一个:

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

and then in your controller: 然后在您的控制器中:

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

and in your view: 并且在您看来:

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM