Laravel 获取所有类别的帖子数
Laravel get all categories with posts count
Hi, I'm trying to get Array contain all Categories with Number of
Posts in each category: Ex:
[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]
详情:
- 帖子Table
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();
});
}
- 类别Table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
- 帖子模型
public function category()
{
return $this->belongsTo('App\Models\Category');
}
- 类别模型
public function posts()
{
return $this->hasMany('App\Models\Post');
}
- 类别控制器
public function index()
{
$Categories = Category::with('posts')->get();
return response()->json($Categories);
}
但是这个函数 return 发布所有文件,是计算它们并将数字作为参数添加到数组中的方法吗?
您可以使用withCount
$categories = Category::withCount('posts')->get();
然后您可以遍历 $categories 并访问
$category->posts_count
每个类别。
Hi, I'm trying to get Array contain all Categories with Number of Posts in each category: Ex:
[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]
详情:
- 帖子Table
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();
});
}
- 类别Table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
- 帖子模型
public function category()
{
return $this->belongsTo('App\Models\Category');
}
- 类别模型
public function posts()
{
return $this->hasMany('App\Models\Post');
}
- 类别控制器
public function index()
{
$Categories = Category::with('posts')->get();
return response()->json($Categories);
}
但是这个函数 return 发布所有文件,是计算它们并将数字作为参数添加到数组中的方法吗?
您可以使用withCount
$categories = Category::withCount('posts')->get();
然后您可以遍历 $categories 并访问
$category->posts_count
每个类别。