Laravel Eloquent - Return 来自条件 hasMany 关系的值数组
Laravel Eloquent - Return array of values from conditional hasMany relationship
我是 PHP 的新手,这让我很震惊。我知道我可以使用原始 SQL 来做到这一点,但我宁愿以正确的方式来做。
我已经建立了关系,它们运行良好。
我有 table 栋房子,如果房子的屋顶是红色的,我想知道这些房子里所有人的名字,但前提是这个人的鞋子是棕色的。
Houses::with('people')
->whereHas('people', function($q){
$q->where('shoes', 'brown');
})->where('roof','red')->get()
这是我所了解的。
房子 Table:
+----+--------+
| id | roof |
+----+--------+
| 1 | red |
| 2 | blue |
| 3 | red |
+----+--------+
人table
+----+----------+-------+-------+
| 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
模型开始。
请注意 whereHas
需要 table 名称,而不是第一个参数中的关系。
$people = People::where('shoes', 'brown')
->whereHas('houses', function ($query) {
$query->where('roof', 'red');
})->get();
我是 PHP 的新手,这让我很震惊。我知道我可以使用原始 SQL 来做到这一点,但我宁愿以正确的方式来做。
我已经建立了关系,它们运行良好。
我有 table 栋房子,如果房子的屋顶是红色的,我想知道这些房子里所有人的名字,但前提是这个人的鞋子是棕色的。
Houses::with('people')
->whereHas('people', function($q){
$q->where('shoes', 'brown');
})->where('roof','red')->get()
这是我所了解的。
房子 Table:
+----+--------+
| id | roof |
+----+--------+
| 1 | red |
| 2 | blue |
| 3 | red |
+----+--------+
人table
+----+----------+-------+-------+
| 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
模型开始。
请注意 whereHas
需要 table 名称,而不是第一个参数中的关系。
$people = People::where('shoes', 'brown')
->whereHas('houses', function ($query) {
$query->where('roof', 'red');
})->get();