我正在创建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
,但我得到的是null。为什么?如您所见,在案例A中返回整个匹配项时,它出现在$match
对象中。
{
"rule": null
}
答案 0 :(得分:2)
乍看之下,我可以看到您像这样(camel case)加载了matchRule
关系:
$match = Match::where("state", 2)
->with("player1", "player2", "points", "matchRule")->first();
^^^^^^^^^^
但是随后您正在访问像这样的关系(snake case):
return response()->json((object) ["rule" => $match->match_rule]);
^^^^^^^^^^^
那些不是等效的。尝试以下方法:
return response()->json((object) ["rule" => $match->matchRule]);
^^^^^^^^^^