簡體   English   中英

Laravel 獲取所有帶有帖子數的類別

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM