User::with([ 'adviser' => function ($query) { $query->select('id', 'name'); }, 'job_log' => function ($query) { $query->select('id', 'sex'); }, 'journal' => function ($query) { $query->select('id', 'name'); }, 'order' => function ($query) { $query->select('user_id', DB::raw("COUNT(*) AS num"), DB::raw("SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END ) AS appropriation_num"), DB::raw("SUM(CASE WHEN status = 2 THEN appropriation_amount ELSE 0 END ) AS appropriation_sum"), DB::raw("SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END ) AS net_income_num"), DB::raw("SUM(CASE WHEN status = 5 THEN net_income ELSE 0 END ) AS net_income_sum")) ->groupBy('user_id'); } ]) ->select('id') ->where('id', $post['id']) ->first();转换成sql语句
时间: 2024-01-28 21:03:36 浏览: 63
这个 Eloquent 查询语句会查询出 ID 为 `$post['id']` 的用户,并预加载它们的 `adviser`、`job_log`、`journal` 和 `order` 关联模型,其中 `order` 模型会使用聚合函数进行统计。下面是这个查询语句转换成 SQL 的样子:
```sql
select `id`
from `users`
where `id` = ?
limit 1
select `id`, `name`
from `advisers`
where `advisers`.`user_id` in (?)
select `id`, `sex`
from `job_logs`
where `job_logs`.`user_id` in (?)
select `id`, `name`
from `journals`
where `journals`.`user_id` in (?)
select `user_id`, COUNT(*) AS num,
SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS appropriation_num,
SUM(CASE WHEN status = 2 THEN appropriation_amount ELSE 0 END) AS appropriation_sum,
SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) AS net_income_num,
SUM(CASE WHEN status = 5 THEN net_income ELSE 0 END) AS net_income_sum
from `orders`
where `orders`.`user_id` in (?)
group by `user_id`
```
其中 `?` 是绑定参数,值取决于查询语句中的占位符数量。这个查询语句会先查询出 ID 为 `$post['id']` 的用户,然后再分别查询出它们的 `adviser`、`job_log`、`journal` 和 `order` 关联模型,其中 `order` 模型会使用聚合函数进行统计。
阅读全文