小编AiA*_*him的帖子

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

嗨,我试图让 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', …
Run Code Online (Sandbox Code Playgroud)

php sql laravel laravel-6

5
推荐指数
1
解决办法
261
查看次数

标签 统计

laravel ×1

laravel-6 ×1

php ×1

sql ×1