【发布时间】:2019-05-12 16:41:18
【问题描述】:
我正在创建 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,但我得到了空值。为什么?如您所见,在情况 A 中返回整个匹配项时,它存在于 $match 对象中。
{
"rule": null
}
【问题讨论】:
标签: php laravel eloquent eloquent-relationship