首页 > 解决方案 > 在 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
}

标签: phplaraveleloquenteloquent-relationship

解决方案


乍一看,我可以看到您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]);
                                                    ^^^^^^^^^^

推荐阅读