显示每个类别的最后一篇文章

时间:2018-01-02 06:45:21

标签: laravel

我有两个模型Post和Category

//迁移帖子

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        $table->string('image');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->timestamps();
    });
}

//迁移类别

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

如何只显示主页中每个类别的最后一篇文章?

3 个答案:

答案 0 :(得分:3)

Hiren很接近,但您需要离开该类别,因为post拥有category

$category->posts()->latest()->first();

或者你可以倒退:

$post = Post::latest()->whereHas('category', function($q) use($category_id) {
    return $q->where('id', $category_id);
})->first();

为此,您需要定义模型关系:

类别模型需要此功能:

public function posts() 
{
    return $this->hasMany(App\Post::class);
}

Post Model需要此功能:

public function category()
{
    return $this->belongsTo(App\Category::class);
}

要回复Alexey Mezenin,我们只需将回调传递给with()即可定义我们要为每个类别添加哪些帖子,并执行正确的eager load

Category::with(['posts' => function($q) {
    return $q->latest()->first();
})->get(); 

答案 1 :(得分:1)

使用最新帖子加载类别的雄辩解决方案是在Category模型中创建额外的hasOne()关系:

public function latestPost()
{
    return $this->hasOne(Post::class)->latest();
}

然后使用eager loading

Category::with('latestPost')->get();

这将只为DB生成2个查询。

答案 2 :(得分:0)

public function up()
{
    Schema::create('news', function (Blueprint $table) {
        $table->increments('id');
        $table->string('slug')->unique();
        $table->unsignedInteger('author_id');
        $table->unsignedInteger('category_id');
        $table->string('subject');
        $table->text('short');
        $table->text('content');
        $table->integer('view')->default(0);
        $table->integer('status')->default(0);
        $table->string('image');
        $table->timestamps();

        $table->foreign('author_id')
              ->references('id')->on('users')
              ->onDelete('cascade');
        // $table->foreign('category_id')
        //       ->references('id')->on('categories')
        //       ->onDelete('cascade');
    });
    // Schema::enableForeignKeyConstraints();
}
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}

在控制器中:

    $latestpostlist = News::whereIn('created_at',function($query){
            $query->select(DB::raw('max(created_at)'))
                      ->from('news')
                      ->groupBy('category_id');
    })->get();

在您的情况下,新闻将被发布。该查询对我有用