只从 hasOne 关系中获取字符串

Only get String from hasOne Relation

我有两个模型:

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;
}

所以在我的用户对象的调用中发生了一些神奇的事情,属于食谱。

我相信这是因为您访问了用户关系。默认情况下,Eloquent 实现延迟加载,但是,当您访问 User 关系以获取名称时,整个对象将被加载并附加到您的 Recipe 对象。

要隐藏 json 上的关系,您应该将 属性 添加到模型

上的 $hidden 属性
protected $hidden = ['user'];

您必须将关系方法名称添加到 Recipe 模型中的 $hidden 属性 数组,才能将其从 json 结果中删除。

https://laravel.com/docs/5.1/eloquent-serialization#hiding-attributes-from-json

class Recipe extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['user'];

    /**
     * The appended attributes shown in JSON results.
     *
     * @var array
     */
    protected $appends = ['username'];

    /**
     * The username attribute accessor for JSON results.
     *
     * @var string
     */
    public function getUsernameAttribute()
    {
        return $this->user->name;
    }
}

我认为除了形成您自己的 JSON 结果集之外,没有办法动态地执行此操作。

您还可以将 $hidden 属性 添加到您的 User 模型以从 JSON 结果中删除您想要隐藏的用户属性?这将允许您在不返回敏感信息的情况下使用序列化关系模型。