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

时间:2015-03-19 18:57:08

标签: php laravel eloquent

我需要从除users属性之外的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');
    }
}

我很抱歉在例外情况下使用保加利亚语言

1 个答案:

答案 0 :(得分:1)

查看代码时,运行只是不可能:

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

roles附加到结果。

您应确保不向$appends属性添加任何内容,并且不在代码中的某处加载关系。您还应该确保没有实现自定义toArray()方法,以便在转换为数组时加载此关系。如果您确定不这样做,则应显示完整的代码和您的Laravel版本。

修改

您没有显示使用selectlists启动代码的位置,但是您在许多方法中加载了roles关系 - 例如isEmployee,{{1 }或isEmployee。这就是为什么在转换为数组时使用hasRole的原因。您可能希望编写自定义roles方法,以便在转换为数组时从结果集中删除toArray