
本文旨在讲解如何在 Laravel 8 中使用查询构建器(Query Builder)来实现包含子查询的数据库操作。我们将通过一个实际的例子,演示如何使用 Eloquent 模型的关联关系以及 `withCount` 和 `whereHas` 等方法来构建复杂的查询语句,并提供相应的代码示例和注意事项,帮助开发者更高效地进行数据库操作。
在 Laravel 8 中,使用查询构建器可以方便地构建复杂的 SQL 查询,包括包含子查询的语句。以下将通过一个示例,介绍如何在 Laravel 中实现子查询,并提供两种常用的方法。
示例场景:
假设我们有 posts 表和 post_likes 表,需要查询 posts 表中 id 为 13 的前 5 条数据,并获取每个 post 中 user_id 为 12 的点赞数量。
方法一:使用 withCount 构建子查询
如果已经定义了 Post 和 PostLike 模型,并且在 Post 模型中定义了 likes 关联关系,可以使用 withCount 方法来构建子查询。
-
定义关联关系(如果尚未定义):
在 Post.php 模型中,定义 likes 关联关系:
<?php namespace App/Models; use Illuminate/Database/Eloquent/Model; class Post extends Model { public function likes() { return $this->hasMany(PostLike::class); } }登录后复制 -
使用 withCount 构建查询:
$userId = 12; $postList = Post::query() ->where('id', 13) ->withCount(['likes', 'likes AS post_like' => function ($query) use ($userId) { $query->where('user_id', '=', $userId); }]) ->limit(5) ->get(); // 处理结果 foreach ($postList as $post) { $count = $post['post_like']; // ... }登录后复制代码解释:
- Post::query(): 创建一个 Post 模型的查询构建器实例。
- where(‘id’, 13): 添加一个 where 条件,限制 post 的 id 为 13。
- withCount([‘likes’, ‘likes AS post_like’ => …]): 使用 withCount 方法计算关联关系的数量。
- ‘likes’: 计算所有 likes 关联的数量,结果会存储在 likes_count 属性中。
- ‘likes AS post_like’ => function ($query) use ($userId) { … }: 使用别名 post_like 计算符合特定条件的 likes 关联数量。
- $query->where(‘user_id’, ‘=’, $userId): 添加一个 where 条件,限制 user_id 为指定的值。
- limit(5): 限制结果集的大小为 5。
- get(): 执行查询并返回结果集。
注意事项:
- 使用 withCount 时,需要确保已经定义了正确的关联关系。
- 可以使用别名来指定计数结果的属性名,例如 likes AS post_like。
- 在闭包中使用 $userId 变量时,需要使用 use 关键字将其传递到闭包中。
方法二:使用 whereHas 构建子查询
whereHas 方法用于查询存在满足特定条件的关联关系的记录。
$postList = Post::query()
->whereHas('likes', function ($query) {
$query->where('user_id', 12);
})
->limit(5)
->get();
代码解释:
- Post::query(): 创建一个 Post 模型的查询构建器实例。
- whereHas(‘likes’, function ($query) { … }): 使用 whereHas 方法查询存在 likes 关联关系,并且满足特定条件的记录。
- $query->where(‘user_id’, 12): 添加一个 where 条件,限制 user_id 为 12。
- limit(5): 限制结果集的大小为 5。
- get(): 执行查询并返回结果集。
注意事项:
- whereHas 方法主要用于筛选满足特定关联关系的记录,而不是计算关联关系的数量。
- 如果需要计算关联关系的数量,建议使用 withCount 方法。
总结:
本文介绍了在 Laravel 8 中使用查询构建器构建包含子查询的两种常用方法:withCount 和 whereHas。 withCount 适用于计算关联关系的数量,而 whereHas 适用于筛选满足特定关联关系的记录。开发者可以根据实际需求选择合适的方法来构建复杂的查询语句,从而更高效地进行数据库操作。
代码示例:
// 使用 withCount
$userId = 12;
$postList = Post::query()
->where('id', 13)
->withCount(['likes', 'likes AS post_like' => function ($query) use ($userId) {
$query->where('user_id', '=', $userId);
}])
->limit(5)
->get();
// 使用 whereHas
$postList = Post::query()
->whereHas('likes', function ($query) {
$query->where('user_id', 12);
})
->limit(5)
->get();
以上就是Laravel 8 中使用子查询构建查询语句的详细内容,更多请关注php中文网其它相关文章!


