【发布时间】:2016-10-29 12:54:43
【问题描述】:
我有两个模型:
a) 食谱 b) 用户
每个配方都有一个用户。当(REST)请求配方时,我还想在我的 JSON 答案中获取相关用户的名称,如下所示:
{
"id": 1,
"user_id": 1,
"name": "Recipe Name",
"description": "Description goes here",
"userName": "Testuser"
}
我得到的是:
{
"id": 1,
"user_id": 1,
"name": "Recipe Name",
"description": "Description goes here",
"userName": "Testuser",
"user": {
"id": 1,
"name": "Testuser",
"email": "mail@example.com"
}
}
这是我在 RecipeController 中的函数:
public function show($id) {
$recipe = Recipe::find($id);
$recipe->userName = (string) $recipe->user->name;
return $recipe;
}
我的配方模型具有以下带有 getter 的属性:
protected $userName = null;
public function setUserName($userName) {
$this->userName = $userName;
}
有趣的是,当使用此代码片段时,我还将整个用户对象作为 JSON 字符串作为配方 JSON 字符串的一部分:
public function show($id) {
recipe = Recipe::find($id);
$recipe->user->name;
return $recipe;
}
所以在我的用户对象的调用中发生了一些魔法,属于配方。
【问题讨论】:
标签: json laravel eloquent relationship