包含两个表lectors
,lessons
及其雄辩模型Lector
和Lesson
。Lectors
表格内容:
| id | name |
| 1 | John |
| 2 | Jack |
[Lessons
表内容:
| id | state | lector_id |
| 1 | new | 1 |
| 2 | new | 1 |
| 3 | old | 1 |
| 4 | new | 2 |
我想查询数据库以获取每个讲师的新课程和旧课程的提示。示例数据库输出为
| id | name | count_new | count_old |
| 1 | John | 2 | 1 |
| 2 | Jack | 1 | 0 |
在此阶段,我对查询并不特别满意。我希望我的API返回如下所示的JSON结果。那就是我正在努力与流明/口才做的事情。
[
{
"id": 1,
"name": "John",
"count_new": 2,
"count_old": 1
},
{
"id": 2,
"name": "Jack",
"count_new": 1,
"count_old": 0
}
]
我对避免在单独的表中进行查询,然后像在互联网上看到的那样遍历代码中的内容的通用方法感兴趣。好像错了是否可以使用Eloquent提供的API来做到这一点?在文档中找不到太多帮助。我最接近的是subJoin
。
答案在文档中:https://laravel.com/docs/eloquent-relationships#counting-related-models
$result = Lector::withCount([
'lessons as lessonsnew_count' => function (Builder $query) {
$query->where('state', '=', 'new');
},
'lessons as lessons_old_count' => function (Builder $query) {
$query->where('state', '=', 'old');
}])->get();