加入表并查看 laravel 8 中每个类别名称中的类别数

join tables and see the count of categories in each category name in laravel 8

不好意思想问一下。 如果我的语言不整洁,请提前道歉

我有一个类别table 与colom -id (pk) -姓名 -和其他人

我有一个 post table 与colom -id (pk) -category_id(fk)

我想计算每个类别的 post 数量以及 laravel 8 中的类别名称。 这是我的 jquery 但还是错了

$categ = DB::table('posts')
 ->select('category_id', 'categories.id', DB::raw('count(posts.id) as total_product'))
 ->join('categories', 'posts.category_id', '=', 'categories.id')
 ->groupBy('posts.category_id')
 ->get();

有人想帮助我吗?

如果你愿意使用Eloquent,答案就简单多了。

Post would be a model for posts table

Category would be a model for categories table

there would be one-to-one or any other relationship as per requirements between models

假设 CategoryPost 模型之间存在一对多关系 这可以通过在 Category model

中添加一个函数来实现
public function posts()
{
    return $this->hasMany(Post::class);
}

然后你可以使用类似...

Category::withCount('posts')->get()

我假设您在查询中使用了错误的 table 名称,或者可能在问题中输入了错误的 table 名称。

假设您的 post table 名称是 posts,类别 table 是 categories ,那么您的查询应该是:

$categ = DB::table('posts')
 ->select('categories.id', "categories.name", DB::raw("count(posts.id) as total_product"))
 ->join('categories, "posts.category_id', '=', 'categories.id')
 ->groupBy('posts.category_id')
 ->get();

请注意 - 请务必将 table 名称替换为您的 table。

如果您将其用于一次性加载,那么您也可以使用模型关系来获取完整信息,而无需创建自定义查询。

https://laravel.com/docs/8.x/eloquent-relationships

您可以将类别设置为 post 关系。 假设你有模型类别和 Post,那么你可以在类别模型中有以下关系。

public function posts(){
 return $this->hasMany(Post::class, 'category_id', 'id');
} 

然后在您的代码中,您可以使用 $category->posts 获取该类别的 post 集合,并可以使用 $category->posts->count() 获取 post 的计数对于类别。