[英]Retrieving relationship data in Eloquent ORM (Laravel PHP)
I'm creating Laravel app and I'm retrieving data from DB with Eloquent ORM while responding with a JSON response. 我正在创建Laravel应用,并使用Eloquent ORM从数据库检索数据,同时以JSON响应进行响应。 In this example I'm getting matches with some other relevant data by relationship (player1, matchRule...).
在此示例中,我通过关系(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
}
In case A, everything's fine and all relevant data are returned. 在情况A中,一切正常,并返回所有相关数据。 Example:
例:
{
"id": 7,
"some_other_match_property": "something",
...
"match_rule": {
"rule_1": "something",
"rule_2": "something",
}
}
In case B, I'm getting just id of match and it also works just fine. 如果是B,我得到的只是match的ID,它也可以正常工作。
{
"id": 7
}
I case C, I'm trying to get property match_rule
but I'm getting null. 我是C,我想获取属性
match_rule
但我得到的是null。 Why? 为什么? As you can see, it is present in the
$match
object when returning the entire match in case A. 如您所见,在情况A中返回整个匹配项时,它存在于
$match
对象中。
{
"rule": null
}
At first glance I can see that you load your matchRule
relationship like this ( camel case ): 乍一看,我可以看到您像这样加载了
matchRule
关系( 驼峰案例 ):
$match = Match::where("state", 2)
->with("player1", "player2", "points", "matchRule")->first();
^^^^^^^^^^
But then you are accessing the relationship like this instead ( snake case ): 但是然后您访问的是这样的关系( 蛇形 ):
return response()->json((object) ["rule" => $match->match_rule]);
^^^^^^^^^^^
Those are not equivalent. 这些是不相等的。 Try this instead:
尝试以下方法:
return response()->json((object) ["rule" => $match->matchRule]);
^^^^^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.