php - Laravel:使用 where inside(带模型)
问题描述
我有这个控制器:
public function user_predects()
{
$matches=Match::with('Predect')->get();
return ($matches);
}
它是这样获取 json 数据的:
[
{
"id": 1,
"m_date": "2021-02-06 22:00:00",
"home": "Turkey",
"away": "Italy",
"h_goals": 0,
"a_goals": 0,
"predect": [
{
"id": 3,
"user_id": 10,
"match_id": 1,
"h_predect": 1,
"a_predect": 1,
"player_id": 1,
"point": 0,
"created_at": null,
"updated_at": null
},
{
"id": 4,
"user_id": 9,
"match_id": 1,
"h_predect": 2,
"a_predect": 1,
"player_id": 1,
"point": 0,
"created_at": null,
"updated_at": null
现在我想查看相同的 json 数据,但只针对一个用户,我使用了这个但不起作用:
public function user_predects($username)
{
$user = User::where('username',$username)->get()
$matches=Match::with('Predect')->where('Predect.user_id',$user[0]->id)->get();
return ($matches);
}
如何查看一个用户的匹配模型和预测模型?
解决方案
试试这个:
public function user_predects($username)
{
$user = User::where('username',$username)->first()
$matches = Match::with(['Predect' => function($query) use ($user) {
return $query->where('Predect.user_id', $user->id);
}])->get();
return ($matches);
}
您还可以从官方文档中阅读有关约束 Eager Loading 的信息:Constraining Eager Loads
推荐阅读
- java - Java 在容器中的应用程序。从控制台启用 TRACE 日志级别
- cqrs - AxonIQ 在重播旧事件的同时处理新事件
- python - GET 和/或 BeautifulSoup FanDuel 网络抓取的接收证书/403 错误
- excel - 根据单元格值显示/隐藏列
- python - 正则表达式/Beautifulsoup HTML 解析
- c - C中系统调用的奇怪行为
- javascript - 如何转换嵌入了 URL 编码的 URL?
- javascript - JavaScript/Chrome 扩展在第二个插槽中打开一个新选项卡
- javascript - 挣扎于布局(使用 styled-components )
- python - mypy 类型和可选过滤