[英]Laravel get all categories with posts count
嗨,我试图让 Array 包含所有类别以及每个类别中的帖子数:例如:
[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]
细节:
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();
});
}
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);
}
但是这个函数返回所有提交的帖子,是计算它们并在数组中添加数字作为参数的方法吗?
您可以使用withCount
$categories = Category::withCount('posts')->get();
然后你可以循环遍历 $categories 并访问
$category->posts_count
在每个类别上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.