[英]Laravel Eloquent hasMany\hasOne limit parents to children with records
使用Laravel Eloquent和hasOne()\\ hasMany()关系,是否可以将“父”表限制为仅在存在“ child \\ foreign”关系的情况下才检索结果?
FOOS
+----+------------+
| id | etc |
+----+------------+
| 1 | one |
| 2 | two |
| 3 | three |
| 4 | four |
+----+------------+
BARS
+----+-----+--------+
| id | val | foo_id |
+----+-----+--------+
| 11 | 101 | 1 |
| 12 | 102 | 2 |
| 13 | 203 | 3 |
| 14 | 204 | 4 |
+----+-----+--------+
在Foo类(模型)中
public function highBars(){
return $this->hasOne('App\Bar')->where('val','>','200');
}
在控制器中
Foo::with('highBars')->get();
返回所有FOOS,即使某些high_bars
关系为null。 是否可以仅包含关系值不为null的FOOS结果? (foos.id = 3,4)
检索...
0 => array:3 [▼
"id" => 1
"etc" => "one"
"high_bars" => null
]
1 => array:3 [▼
"id" => 2
"etc" => "two"
"high_bars" => null
]
2 => array:3 [▼
"id" => 3
"etc" => "three"
"high_bars" => array:2 [▼
"id" => 13
"val" =>203
"foo_id" =>3
]
]
3 => array:3 [▼
"id" => 4
"etc" => "four"
"high_bars" => array:2 [▼
"id" => 14
"val" =>204
"foo_id" =>4
]
]
但这就是我想要的
0 => array:3 [▼
"id" => 3
"etc" => "three"
"high_bars" => array:2 [▼
"id" => 13
"val" =>203
"foo_id" =>3
]
]
1 => array:3 [▼
"id" => 4
"etc" => "four"
"high_bars" => array:2 [▼
"id" => 14
"val" =>204
"foo_id" =>4
]
]
引用文档 。
访问模型的记录时,您可能希望根据关系的存在来限制结果。 例如,假设您要检索所有具有至少一条评论的博客文章。 为此,您可以将关系的名称传递给has方法:
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
您还可以指定一个运算符并计数以进一步自定义查询:
// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();
嵌套的has语句也可以使用“点”符号构造。 例如,您可以检索所有具有至少一项评论和投票的帖子:
// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();
如果您需要更多功能,则可以使用whereHas和orWhereHas方法在您的条件查询中放置“ where”条件。 这些方法使您可以向关系约束中添加自定义约束,例如检查注释的内容:
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
对于您的特定示例,这可以通过使用以下方法实现:
Foo::has('highBars')->get();
这还不够。 定义关系时,您只需要告诉Laravel哪些数据与实体相关联,但这并不会限制数据的获取方式。
因此,当您在控制器中执行操作时
Foo::with('highBars')->get();
这里的关键是这个get
。 您只是将其限制为任何内容,只是说,让我拥有所有行,并且除此以外,获取与此模型关联的数据。 您需要做的是添加一个约束。
Foo::with('highBars')->whereHas('highBars', function ($query) {
$query->where('val', '>', '200');
})->get();
或快捷方式将是
Foo::has('highBars')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.