2017-01-30 51 views
0

我只是试图在json响应中包含一个新的属性,但由于某种原因我也获得了对象关系。

// user model 
protected $guarded = ['id']; 
protected $appends = ['role_name']; 
protected $hidden = ['remember_token', 'password']; 

public function getRoleNameAttribute() 
{ 
    return $this->role->type; 
} 

public function role() 
{ 
    return $this->belongsTo(Role::class); 
} 

// role model 
public function users() 
{ 
    return $this->hasMany(User::class); 
} 

当我使用dd($user);我得到

User {#303 
    #guarded: array:1 [ 
    0 => "id" 
    ] 
    #appends: array:1 [ 
    0 => "role_name" 
    ] 
    #hidden: array:2 [ 
    0 => "remember_token" 
    1 => "password" 
    ] 
    #connection: null 
    #table: null 
    #primaryKey: "id" 
    #keyType: "int" 
    #perPage: 15 
    +incrementing: true 
    +timestamps: true 
    #attributes: array:7 [ 
    "name" => "testing" 
    "email" => "[email protected]" 
    "password" => "$2y$10$fogQXhJZm5eoViM38pge1.BmNxY7IFl515zT83.Ks9Uj26kK9T6Im" 
    "role_id" => "83eee2e0-8939-48f7-9fbc-1c077e2265e5" 
    "id" => "a181fb4b-b65a-47b4-9c72-21ea15c6c5a6" 
    "updated_at" => "2017-01-30 20:23:52" 
    "created_at" => "2017-01-30 20:23:52" 
    ] 
    #original: array:7 [ 
    "name" => "testing" 
    "email" => "[email protected]" 
    "password" => "$2y$10$fogQXhJZm5eoViM38pge1.BmNxY7IFl515zT83.Ks9Uj26kK9T6Im" 
    "role_id" => "83eee2e0-8939-48f7-9fbc-1c077e2265e5" 
    "id" => "a181fb4b-b65a-47b4-9c72-21ea15c6c5a6" 
    "updated_at" => "2017-01-30 20:23:52" 
    "created_at" => "2017-01-30 20:23:52" 
    ] 
    ... 
} 

return response()->json(compact('user'));相反,我得到

user: { 
    created_at: "2017-01-30 20:26:12" 
    email:"[email protected]" 
    id:"4b83e031-e8c8-4050-963d-446cb383fb14" 
    name:"testing" 
    role:{ 
     created_at:"2016-12-29 10:54:02" 
     id:"83eee2e0-8939-48f7-9fbc-1c077e2265e5" 
     type:"user" 
     updated_at:"2016-12-29 10:54:02" 
    } 
    role_id:"83eee2e0-8939-48f7-9fbc-1c077e2265e5" 
    role_name:"user" 
    updated_at:"2017-01-30 20:26:12" 
} 

但我希望是只有

user: { 
    created_at: "2017-01-30 20:26:12" 
    email:"[email protected]" 
    id:"4b83e031-e8c8-4050-963d-446cb383fb14" 
    name:"testing" 
    role_id:"83eee2e0-8939-48f7-9fbc-1c077e2265e5" 
    role_name:"user" 
    updated_at:"2017-01-30 20:26:12" 
} 

所以我没有确定这是正常行为还是错误,或者可能是错过了什么?

  • Laravel版本30年3月5日
+0

如何获取$ user? – Vikash

+0

这是已创建用户的返回对象ex.' $ user = User :: create([...]);' – ctf0

回答

2

为什么发生这种情况的原因是以下

public function getRoleNameAttribute() 
{ 
    return $this->role->type; 
} 

的这里的问题是,当你说$this->role它会自动连接到关系模型。为了防止这种情况发生,您应该直接访问该方法,如$this->role()

public function getRoleNameAttribute() 
{ 
    return $this->role()->first()->type; 
} 
+0

第一个给出了'未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ type ',第二次按预期工作,thanx – ctf0