php - 在 Eloquent ORM (Laravel PHP) 中检索关系数据
问题描述
我正在创建 Laravel 应用程序,我正在使用 Eloquent ORM 从数据库中检索数据,同时使用 JSON 响应进行响应。在这个例子中,我通过关系(player1,matchRule ...)获取与其他一些相关数据的匹配。
public function test() {
$match = Match::where("state", 2)
->with("player1", "player2", "points", "matchRule")->first();
return response()->json($match); // CASE A
return response()->json((object) ["id" => $match->id]); // CASE B
return response()->json((object) ["rule" => $match->match_rule]); // CASE C
}
在情况 A 中,一切正常,所有相关数据均已返回。例子:
{
"id": 7,
"some_other_match_property": "something",
...
"match_rule": {
"rule_1": "something",
"rule_2": "something",
}
}
在案例 B 中,我得到的只是匹配的 id,它也可以正常工作。
{
"id": 7
}
我的情况是 C,我试图获得财产match_rule
,但我得到了空值。为什么?如您所见,$match
在案例 A 中返回整个匹配项时,它存在于对象中。
{
"rule": null
}
解决方案
乍一看,我可以看到您matchRule
像这样加载您的关系(骆驼案例):
$match = Match::where("state", 2)
->with("player1", "player2", "points", "matchRule")->first();
^^^^^^^^^^
但随后您正在访问这样的关系(蛇案例):
return response()->json((object) ["rule" => $match->match_rule]);
^^^^^^^^^^^
这些是不等价的。试试这个:
return response()->json((object) ["rule" => $match->matchRule]);
^^^^^^^^^^
推荐阅读
- firebase - 如何使用 userDeletionRequests:upsert 从 Firebase 中删除用户分析数据,因为“APP_INSTANCE_ID”被标记为已弃用?
- r - 计算R中矩阵中团队的出现次数
- google-bigquery - 从 REGEXP_REPLACE 安全地转换正则表达式匹配
- php - 当我在 wordpress functions.php 中导入另一个版本的那个时,Jquery 不起作用
- java - java.security.SignatureException:对象未初始化以进行签名
- python - 如何对数据框列中的多个值求和,如果它们对应于另一列中的 1 个值
- google-sheets - 如何使用 arrayformula 引用以前的匹配记录?
- angular - textarea中JSON格式的格式字符串?
- msbuild - MSBuild 在错误的地方寻找 Microsoft.VisualBasic.Core.targets
- mysql - 未正确编码的 unicode 值