我只是試圖在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日
如何獲取$ user? – Vikash
這是已創建用戶的返回對象ex.' $ user = User :: create([...]);' – ctf0