【问题标题】:Only get String from hasOne Relation仅从 hasOne Relation 中获取 String
【发布时间】: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


    【解决方案1】:

    您必须将关系方法名称添加到 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 结果中隐藏的用户属性?这将允许您在不返回敏感信息的情况下利用序列化关系模型。

    【讨论】:

    • 谢谢!这适用于特定情况,但有时我需要我的食谱模型中的整个用户对象。 “按需”完成它的最佳方式是什么?
    【解决方案2】:

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

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

    protected $hidden = ['user'];
    

    【讨论】:

    • 不幸的是,这不起作用。只要我调用对用户名的访问,整个用户对象就会附加到 JSON 字符串,无论我在提取字符串后是否将其设置为 null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多