Laravel 获取所有带有帖子数的类别

AiA*_*him 5 php sql laravel laravel-6

嗨,我试图让 Array 包含所有类别以及每个类别中的帖子数:例如:

[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]
Run Code Online (Sandbox Code Playgroud)

细节:

  • 帖子表
[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]
Run Code Online (Sandbox Code Playgroud)
  • 类别表
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('slug')->unique();
        $table->string('title');
        $table->string('image');
        $table->text('description');
        $table->integer('category_id')->unsigned();;
        $table->longText('content');
        $table->boolean('published')->default(0);
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)
  • 帖子模型
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)
  • 类别模型
public function category()
{
  return $this->belongsTo('App\Models\Category');
}
Run Code Online (Sandbox Code Playgroud)
  • 分类控制器
public function posts()
{
  return $this->hasMany('App\Models\Post');
}
Run Code Online (Sandbox Code Playgroud)

但是这个函数返回所有提交的帖子,是计算它们并在数组中添加数字作为参数的方法吗?

por*_*s Ψ 5

您可以使用withCount

$categories = Category::withCount('posts')->get(); 
Run Code Online (Sandbox Code Playgroud)

然后你可以循环 $categories 并访问

$category->posts_count 
Run Code Online (Sandbox Code Playgroud)

在每个类别上。