
本教程将详细介绍如何在 laravel 8 中使用 eloquent orm 高效统计每个分类下的文章数量。通过定义模型关联和利用 `withcount` 方法,开发者可以避免手动编写复杂的 sql 查询,以简洁、可读性强的方式获取每个分类及其关联文章的总数,极大提升开发效率和代码质量。
在 Laravel 应用开发中,统计关联模型的数据量是一个非常常见的需求,例如统计每个分类下的文章数量、每个用户发布的评论数量等。虽然可以通过 DB 查询构造器结合 JOIN 和 GROUP BY 来实现,但 Laravel 的 Eloquent ORM 提供了更优雅、更高效的解决方案,即利用模型关系和 withCount 方法。
1. 定义数据库表结构
为了演示,我们假设存在以下两个表:
categories 表:存储文章分类信息。id (主键)name (分类名称)...其他字段posts 表:存储文章信息。id (主键)category_id (外键,关联 categories.id)...其他字段2. 创建并定义 Eloquent 模型
首先,我们需要为这两个表创建对应的 Eloquent 模型。
// app/Models/Category.phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class Category extends Model{ use HasFactory; protected $fillable = ['name']; public function posts() { return $this->hasMany(Post::class); }}登录后复制// app/Models/Post.phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class Post extends Model{ use HasFactory; protected $fillable = ['title', 'content', 'category_id']; public function category() { return $this->belongsTo(Category::class); }}登录后复制在 Category 模型中,我们定义了一个 posts 方法,它返回 hasMany(Post::class),表示一个 Category 可以拥有多个 Post。这是实现统计关联数量的关键。
3. 使用 withCount 方法统计关联数量
Laravel Eloquent 提供的 withCount 方法是统计关联模型数量的利器。它会在查询结果中为每个父模型实例添加一个 [relation]_count 属性,其中包含关联模型的数量。
要统计每个分类下的文章数量,只需在查询 Category 模型时使用 withCount('posts'):
盘古大模型 华为云推出的一系列高性能人工智能大模型
35 查看详情
use App\Models\Category;$categoriesWithPostCount = Category::withCount('posts')->get();foreach ($categoriesWithPostCount as $category) { echo "分类名称: " . $category->name . ",文章数量: " . $category->posts_count . "\n";}Category::withCount('posts'):这条语句指示 Eloquent 在获取 Category 模型时,同时统计每个分类关联的 posts 数量。get():执行查询并返回一个 Category 模型的集合。$category-youjiankuohaophpcnposts_count:对于集合中的每一个 Category 模型实例,withCount('posts') 会自动添加一个名为 posts_count 的属性,其值就是该分类下关联文章的总数。这个属性的命名规则是:关联方法名(此处为 posts)后加上 _count。4. 优势与注意事项
4.1 优势
简洁性: 相比于手动编写 JOIN 和 GROUP BY 的 SQL 语句,withCount 方法的代码更加简洁、易读。性能优化: withCount 在底层会生成一条高效的 SQL 查询,通常是使用子查询或左连接,避免了加载所有关联模型到内存中再进行计数,从而提高了性能。可维护性: 将业务逻辑封装在 Eloquent 模型中,提高了代码的可维护性和复用性。灵活性: 可以链式调用其他 Eloquent 查询方法,如 where、orderBy 等,进一步筛选或排序结果。4.2 带有条件的计数
如果你需要统计满足特定条件的关联模型数量,可以在 withCount 中传入一个闭包函数:
use App\Models\Category;// 统计每个分类下状态为 'published' 的文章数量$categoriesWithPublishedPostCount = Category::withCount(['posts' => function ($query) { $query->where('status', 'published');}])->get();foreach ($categoriesWithPublishedPostCount as $category) { echo "分类名称: " . $category->name . ",已发布文章数量: " . $category->posts_count . "\n";}登录后复制在这个例子中,posts_count 将只包含 status 字段为 'published' 的文章数量。
4.3 多个关联计数
你也可以同时统计多个关联模型的数量:
use App\Models\Category;// 假设 Category 模型还有一个 comments 关联$categoriesWithCounts = Category::withCount(['posts', 'comments'])->get();foreach ($categoriesWithCounts as $category) { echo "分类名称: " . $category->name . ",文章数量: " . $category->posts_count . ",评论数量: " . $category->comments_count . "\n";}登录后复制总结
通过本教程,我们学习了如何在 Laravel 8 中利用 Eloquent ORM 的 withCount 方法高效地统计关联模型的数量。这种方法不仅使代码更加简洁和富有表现力,而且在性能上也进行了优化,是处理此类需求的首选方案。掌握 withCount 及其条件计数功能,将极大提升你在 Laravel 项目中的开发效率和代码质量。
以上就是Laravel Eloquent 教程:高效统计关联模型数量(以分类文章为例)的详细内容,更多请关注php中文网其它相关文章!



