出于某些奇怪的原因,我的Laravel 5.6应用程序继续返回一个包含所有关系的User对象。
我在Api/UserController
中的查询:
public function show($user_id)
{
return User::with('meta', 'roles')->find($user_id);
}
回应:
{
"id": 1,
"name": "Admin",
"email": "admin@example.com",
"company_id": 1,
"meta": {
"id": 1,
"user_id": 1,
"laptop": 0,
"mobile": 0,
"created_at": "2018-03-07 14:58:41",
"updated_at": "2018-04-06 16:13:10"
},
"roles": [
{
"id": 2,
"name": "admin",
"label": "Admin",
"permissions": null,
"pivot": {
"user_id": 1,
"role_id": 2
}
}
],
"company": {
"id": 1,
"name": "Company",
"active": 1,
"created_at": "2018-04-12 15:06:01",
"updated_at": "2018-05-15 11:20:15",
"is_max_user_limit_reached": true
}
}
路线(在routes/api.php
内):
Route::group(['middleware' => 'auth:api'], function () {
Route::resource('/users', 'Api\UserController', ['as' => 'api']);
});
用户模型:
namespace App\Models;
use App\Models\Role;
class User extends Authenticatable implements HasMedia
{
use HasApiTokens, Notifiable, Billable, HasMediaTrait;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password', 'is_active', 'company_id', 'stripe_id', 'card_brand', 'card_last_four', 'trial_ends_at'];
protected $hidden = ['password', 'remember_token','card_brand', 'card_last_four'];
protected $appends = ['extra', 'is_staff_only', 'first_four_training_sections', 'is_free_tier', 'is_agency_tier', 'is_team_tier', 'is_enterprise_tier'];
public static $rules = [
// create rules
'name' => 'required',
'email' => 'required|email|unique:users'
];
public function meta()
{
return $this->hasOne(UserMeta::class);
}
public function company()
{
return $this->belongsTo(Company::class, 'company_id')->where('active', 1);
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function getExtraAttribute()
{
return [
'roles' => [
'cpo' => (int)$this->hasRole('cpo'),
'ap' => (int)$this->hasRole('ap'),
'cao' => (int)$this->hasRole('cao'),
]
];
}
public function getIsStaffOnlyAttribute()
{
if($this->roles->count() == 1 && $this->hasRole('staff')) {
return true;
}
return false;
}
public function getIsFreeTierAttribute()
{
return $this->company->subscription_tier == 0;
}
public function getIsAgencyTierAttribute()
{
return $this->company->subscription_tier == 1;
}
public function getIsTeamTierAttribute()
{
return $this->company->subscription_tier == 2;
}
public function getIsEnterpriseTierAttribute()
{
return $this->company->subscription_tier == 3;
}
public function getFirstFourTrainingSectionsAttribute() {
return UserTrainingSection::where('user_id', $this->id)->orderBy('id')->take(4)->get();
}
}
这是非常奇怪的行为。我只要求roles
和meta
相关数据,但它始终返回用户模型上的每个关系。
即使我尝试User::find($user_id);
,它仍会返回所有关系。
任何人都知道这里发生了什么?
我正在使用Laravel 5.6和PHP 7.2
答案 0 :(得分:0)
您可以使用$hidden
属性从响应中删除关系:
protected $hidden = ['company', ...];
您也可以暂时删除关系:
$user->addHidden('company');