我正在尝试通过计数(孩子)和所有主人生,与groupby一起获得laravel的主要孩子。下面是表记录和laravel代码。
父表
String[] command1 = {"bash", "-c", "/archive/scripts/grep.pl /apps/ws/logs/*"};
儿童表
+-------------+------------+
| Id | Name |
+-------------+------------+
| 1 | a |
+-------------+------------+
| 2 | b |
+-------------+------------+
| 3 | c |
+-------------+------------+
结果 如果子节点的主节点ID不是0,则计算子节点中所有相同的父节点并显示所有主节点ID。
+-------------+------------+
| parent_Id | Code |
+-------------+------------+
| 1 | d1 |
+-------------+------------+
| 1 | d1 |
+-------------+------------+
| 1 | d1 |
+-------------+------------+
| 1 | d1 |
+-------------+------------+
| 2 | d2 |
+-------------+------------+
| 2 | d3 |
+-------------+------------+
现在我的laravel雄辩如下。
+-------------+----------------------+
|countparentIds in child| parentName
+-------------+----------------------+
| 6 | a |
+-------------+----------------------+
| 2 | b |
+-------------+----------------------+
| 0 | c |
+-------------+----------------------+
现在我得到结果,父表所有行,并计算具有父ID的子。
答案 0 :(得分:0)
尝试 CASE WHEN
喜欢这个
$ter = DB::table('parents')
->leftjoin('child', 'parent.id', '=', 'child.parent_id')
->select(array('parent.name as Name', DB::raw('CASE WHEN (child.code= "d1") THEN COUNT(child.parent_id) ELSE 0 END as countparentids')))
->orderBy('parent.name')
->groupBy('parent.name')
->get();