如何正确隐藏模型关系,以免返回toArray()或toJson()? [英] How do I correctly hide model relationships from returning in toArray() or toJson()?
问题描述
我目前正在开发一个正在编写API的项目,并且在许多模型中,我试图隐藏它们的父级关系,就像这样
I'm currently working on a project where I'm writing an API, and with a lot of the models, I'm trying to hide their parent relationships from being returned, like so
<?php namespace Viper\Model;
class User_Token extends Eloquent {
protected $table = 'users_tokens';
protected $fillable = array(
'user_id', 'token'
);
protected $hidden = array(
'id', 'user_id', 'user'
);
public function user() {
return $this->belongsTo('User');
}
}
在Laravel文档中,对于 Eloquent>转换为数组或Json部分,其中明确指出
In the Laravel documentation, for the Eloquent > Converting to Array or Json section, it clearly says
注意:隐藏关系时,请使用关系的方法名称,不是动态访问者名称.
Note: When hiding relationships, use the relationship's method name, not the dynamic accessor name.
这到底是什么意思?在上面的示例中,方法名称和动态访问器名称都相同,并且我一辈子都想不到,请考虑一下情况并非如此.
What exactly does this mean? In the above example, both the method name and the dynamic accessor name are the same, and I can't for the life of me, think of a situation where this wouldn't be the case.
推荐答案
protected $hidden = array(
'id', 'user_id', 'user'
^^^ relationship's method name which is "user"
);
如果要隐藏关系,则必须在隐藏属性下包括方法名称
.从隐藏属性中,我可以看到,您正在从Array和JSON conversion完美隐藏 user
关系.但是,如果您在 users_tokens
表中具有用户"列,则我不知道Laravel的行为.
if you want to hide the relationship , you have to include method name
under hidden attributes. From your hidden attributes, i can see, you are perfectly hiding user
relationship from Array and JSON conversion . However, if you have 'user' column in your users_tokens
table, I have no idea what Laravel will behave.
public function user() {
return $this->belongsTo('User');
}
这篇关于如何正确隐藏模型关系,以免返回toArray()或toJson()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!