我对PHP相当陌生,这真的让我感到震惊。我知道我可以使用原始SQL做到这一点,但我宁愿以正确的方式做到这一点。
我已经建立了关系,并且它们工作正常。
我有一张桌子,如果这些房子的屋顶是红色的,但只有当这个人的鞋子是棕色的时候,我想获得这些房子中所有人的名字。
Houses::with('people')->whereHas('people', function($q){$q->where('shoes', 'brown');})->where('roof','red)->get()
据我所知。
房屋表:
+----+--------+
| id | roof |
+----+--------+
| 1 | red |
| 2 | blue |
| 3 | red |
+----+--------+
人物表
+----+----------+-------+-------+
| id | house_id | shoes | name |
+----+----------+-------+-------+
| 1 | 1 | brown | paul |
| 2 | 1 | brown | susie |
| 3 | 2 | red | bob |
| 4 | 2 | brown | kate |
| 5 | 3 | brown | frank |
+----+----------+-------+-------+
我想要的输出是这样的人物名称数组:
[paul, susie, frank]
我觉得我整天都在撞墙
请尝试:
$people = People::where('shoes', 'brown')
->whereHas('houses', function ($query) {
$query->where('roof', 'red');
})->get();