2017-01-30 63 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