如何 select 用户,角色除外 Laravel Eloquent
How to select users except roles with Laravel Eloquent
我只需要 select 来自用户 table 的 id 和 name 属性,角色属性除外。我试过这个:
$school_user = User::select('name', 'id')->get()->toArray();
但是当我打印它以筛选它时 returns 包含他的角色的数组。像这样:
Array
(
[0] => Array
(
[name] => Admin
[id] => 1
[roles] => Array
(
[0] => Array
(
[id] => 3
[name] => admin
[pivot] => Array
(
[user_id] => 1
[role_id] => 1
)
)
)
)
)
关于仅获取名称和 ID 属性(角色除外)的任何建议?
有我的用户模型class(有点干净):
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array('email', 'name', 'password', 'block');
protected $guarded = array('id');
/**
* Get the schools or kindergardens a user can moderate
*/
public function schools()
{
return $this->belongsToMany('School', 'school_user');
}
/**
* Get the roles a user has
*/
public function roles()
{
return $this->belongsToMany('Role', 'users_roles');
}
/**
* Find out if User is an employee, based on if has any roles
*
* @return boolean
*/
public function isEmployee()
{
$roles = $this->roles->toArray();
return !empty($roles);
}
/**
* Find out if user has a specific role
*
* $return boolean
*/
public function hasRole($check)
{
return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}
/**
* Get key in array with corresponding value
*
* @return int
*/
private function getIdInArray($array, $term)
{
foreach ($array as $key => $value) {
if ($value['name'] == $term) {
return $key;
}
}
throw new UnexpectedValueException;
}
/**
* Add roles to user to make them a concierge
*/
public function makeEmployee($role_id)
{
$assigned_roles = array();
$roles = Role::all()->keyBy('id')->toArray();
$this->roles()->attach(array($role_id));
}
public $invitation;
protected static function boot()
{
parent::boot();
static::creating(function($model)
{
$data = array(
'invitation' => $model->invitation,
'email' => $model->email,
'name' => $model->name,
'password' => $model->password
);
$model->password = Hash::make($model->password);
$rules = array(
'invitation' => 'required',
'email' => 'unique:users,email|required|email',
'name' => 'required|min:3|max:20',
'password' => 'required|min:8|max:30'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator->messages());
} else {
return $model->validate();
}
});
static::created(function($model)
{
$role_id = Invitation::where('code', '=', $model->invitation)->first()->role_id;
$model->makeEmployee($role_id);
$invitation_code = Invitation::where('code', '=', $model->invitation)->update(array('used_by' => $model->id));
});
}
public function validate()
{
if (is_null(Invitation::where('code', '=', $this->invitation)->where('used_by', '=', '0')->first())) {
throw new ValidationException(null, null, null, array('invitation' => "Грешен код."));
} else {
return true;
}
}
public function updatePass($old_password, $new_password, $repeat_new_password)
{
$data = array(
'old_password' => $old_password,
'new_password' => $new_password,
'repeat_new_password' => $repeat_new_password
);
$rules = array(
'old_password' => 'required',
'new_password' => 'required|min:8|max:30',
'repeat_new_password' => 'required|same:new_password'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator);
} else {
$user = User::find(Auth::user()->id);
if (Hash::check($old_password, $user->password)) {
$user->password = Hash::make($new_password);
if($user->save()) {
return true;
} else {
throw new ValidationException(null, null, null, array('mainError' => "Грешка с базата данни."));
}
} else {
throw new ValidationException(null, null, null, array('old_password' => "Моля въведете правилно страта Ви парола."));
}
}
}
public function login($email, $password, $remember)
{
$data = array(
'email' => $email,
'password' => $password
);
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator);
} else {
if (User::where('email', '=', $email)->first()->block == true) {
throw new ValidationException(null, null, null, array('mainError' => "Акаунтът ви е блокиран."));
} else {
$remember = ($remember) ? true : false;
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
return true;
} else {
throw new ValidationException(null, null, null, array('mainError' => 'Имейлът или паролата е грешна.'));
}
}
}
}
}
和榜样:
<?php
class Role extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'roles';
protected $fillable = array('name');
protected $guarded = array('id');
/**
* Set timestamps off
*/
public $timestamps = false;
/**
* Get users with a certain role
*/
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
}
很抱歉在例外情况下使用保加利亚语
查看代码,运行 不太可能只是:
$school_user = User::select('name', 'id')->get()->toArray();
将 roles
添加到结果。
您应该确保没有向 $appends
属性 添加任何内容,并且您没有在代码中的某处加载关系。您还应该确保在转换为数组时没有实现加载此关系的自定义 toArray()
方法。如果你确定你不这样做,你应该显示完整的代码和你的确切 Laravel 版本。
编辑
您没有显示使用 select
或 lists
启动代码的位置,但是您使用许多方法加载 roles
关系 - 例如 isEmployee
,isEmployee
或 hasRole
。这就是为什么在转换为数组时使用 roles
的原因。您可能希望编写自定义 toArray
方法以在转换为数组时从结果集中删除 roles
。
我只需要 select 来自用户 table 的 id 和 name 属性,角色属性除外。我试过这个:
$school_user = User::select('name', 'id')->get()->toArray();
但是当我打印它以筛选它时 returns 包含他的角色的数组。像这样:
Array
(
[0] => Array
(
[name] => Admin
[id] => 1
[roles] => Array
(
[0] => Array
(
[id] => 3
[name] => admin
[pivot] => Array
(
[user_id] => 1
[role_id] => 1
)
)
)
)
)
关于仅获取名称和 ID 属性(角色除外)的任何建议?
有我的用户模型class(有点干净):
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array('email', 'name', 'password', 'block');
protected $guarded = array('id');
/**
* Get the schools or kindergardens a user can moderate
*/
public function schools()
{
return $this->belongsToMany('School', 'school_user');
}
/**
* Get the roles a user has
*/
public function roles()
{
return $this->belongsToMany('Role', 'users_roles');
}
/**
* Find out if User is an employee, based on if has any roles
*
* @return boolean
*/
public function isEmployee()
{
$roles = $this->roles->toArray();
return !empty($roles);
}
/**
* Find out if user has a specific role
*
* $return boolean
*/
public function hasRole($check)
{
return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}
/**
* Get key in array with corresponding value
*
* @return int
*/
private function getIdInArray($array, $term)
{
foreach ($array as $key => $value) {
if ($value['name'] == $term) {
return $key;
}
}
throw new UnexpectedValueException;
}
/**
* Add roles to user to make them a concierge
*/
public function makeEmployee($role_id)
{
$assigned_roles = array();
$roles = Role::all()->keyBy('id')->toArray();
$this->roles()->attach(array($role_id));
}
public $invitation;
protected static function boot()
{
parent::boot();
static::creating(function($model)
{
$data = array(
'invitation' => $model->invitation,
'email' => $model->email,
'name' => $model->name,
'password' => $model->password
);
$model->password = Hash::make($model->password);
$rules = array(
'invitation' => 'required',
'email' => 'unique:users,email|required|email',
'name' => 'required|min:3|max:20',
'password' => 'required|min:8|max:30'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator->messages());
} else {
return $model->validate();
}
});
static::created(function($model)
{
$role_id = Invitation::where('code', '=', $model->invitation)->first()->role_id;
$model->makeEmployee($role_id);
$invitation_code = Invitation::where('code', '=', $model->invitation)->update(array('used_by' => $model->id));
});
}
public function validate()
{
if (is_null(Invitation::where('code', '=', $this->invitation)->where('used_by', '=', '0')->first())) {
throw new ValidationException(null, null, null, array('invitation' => "Грешен код."));
} else {
return true;
}
}
public function updatePass($old_password, $new_password, $repeat_new_password)
{
$data = array(
'old_password' => $old_password,
'new_password' => $new_password,
'repeat_new_password' => $repeat_new_password
);
$rules = array(
'old_password' => 'required',
'new_password' => 'required|min:8|max:30',
'repeat_new_password' => 'required|same:new_password'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator);
} else {
$user = User::find(Auth::user()->id);
if (Hash::check($old_password, $user->password)) {
$user->password = Hash::make($new_password);
if($user->save()) {
return true;
} else {
throw new ValidationException(null, null, null, array('mainError' => "Грешка с базата данни."));
}
} else {
throw new ValidationException(null, null, null, array('old_password' => "Моля въведете правилно страта Ви парола."));
}
}
}
public function login($email, $password, $remember)
{
$data = array(
'email' => $email,
'password' => $password
);
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator);
} else {
if (User::where('email', '=', $email)->first()->block == true) {
throw new ValidationException(null, null, null, array('mainError' => "Акаунтът ви е блокиран."));
} else {
$remember = ($remember) ? true : false;
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
return true;
} else {
throw new ValidationException(null, null, null, array('mainError' => 'Имейлът или паролата е грешна.'));
}
}
}
}
}
和榜样:
<?php
class Role extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'roles';
protected $fillable = array('name');
protected $guarded = array('id');
/**
* Set timestamps off
*/
public $timestamps = false;
/**
* Get users with a certain role
*/
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
}
很抱歉在例外情况下使用保加利亚语
查看代码,运行 不太可能只是:
$school_user = User::select('name', 'id')->get()->toArray();
将 roles
添加到结果。
您应该确保没有向 $appends
属性 添加任何内容,并且您没有在代码中的某处加载关系。您还应该确保在转换为数组时没有实现加载此关系的自定义 toArray()
方法。如果你确定你不这样做,你应该显示完整的代码和你的确切 Laravel 版本。
编辑
您没有显示使用 select
或 lists
启动代码的位置,但是您使用许多方法加载 roles
关系 - 例如 isEmployee
,isEmployee
或 hasRole
。这就是为什么在转换为数组时使用 roles
的原因。您可能希望编写自定义 toArray
方法以在转换为数组时从结果集中删除 roles
。