【问题标题】:Retrieving relationship data in Eloquent ORM (Laravel PHP)在 Eloquent ORM (Laravel PHP) 中检索关系数据
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 哦,是的,你是对的!谢谢!但正如您在案例 A 中看到的那样,$match 对象中的属性名称是 match_rule 那么为什么我无法通过 ->match_rule 访问它?
    • @P.N.我认为 Laravel 中的默认行为是在作为属性获取关系的蛇版本(函数名称)时。检查this thread,提到可以禁用设置为false模型的$snakeAttributes属性:public static $snakeAttributes = false;。试一试,然后回来告诉我们它是否有效。祝你有美好的一天。
    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 2022-07-27
    • 2021-01-10
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2013-09-28
    相关资源
    最近更新 更多