如何使用Laravel Eloquent选择除角色之外的用户


How to select users except roles with Laravel Eloquent

除了角色属性,我只需要从users表中选择id和name属性。我试过这个:

$school_user = User::select('name', 'id')->get()->toArray();

但当我把它打印到屏幕上时,它会返回带有他的角色的数组。像这样:

Array
(
    [0] => Array
        (
            [name] => Admin
            [id] => 1
            [roles] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => admin
                            [pivot] => Array
                                (
                                    [user_id] => 1
                                    [role_id] => 1
                                )
                        )
                )
        )
)

有没有建议只获取除角色之外的名称和id属性?

这里有我的用户模型类(有点干净):

<?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();

将CCD_ 1附加到结果中。

您应该确保没有向$appends属性添加任何内容,也没有在代码中的某个位置加载关系。您还应该确保没有实现在转换为数组时加载此关系的自定义toArray()方法。如果你确定你没有,你应该显示完整的代码和你的确切的Laravel版本。

编辑

您没有显示在哪里使用selectlists启动代码,但是您可以用许多方法加载roles关系,例如isEmployeeisEmployeehasRole。这就是在转换为数组时使用roles0的原因。您可能需要编写自定义toArray方法,以便在转换为数组时从结果集中删除roles