【问题标题】:How to select users except roles with Laravel Eloquent如何使用 Laravel Eloquent 选择角色以外的用户
【发布时间】:2015-05-23 01:15:39
【问题描述】:

我只需要从 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');
    }
}

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

【问题讨论】:

  • 你的口才模特怎么样?
  • 我用雄辩的模型更新我的问题。
  • 不确定,因为您的模型中的关系。您是否尝试过使用列表?
  • 是的,列表非常适合我。谢谢老兄:)
  • 我实际上已经测试过你的代码。在修补程序中,我得到了预期的结果。

标签: php laravel eloquent


【解决方案1】:

查看代码,运行起来是不可能的:

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

将roles 附加到结果中。

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

编辑

您没有显示使用 select 或 lists 启动代码的位置,但是您通过多种方法加载 roles 关系 - 例如 isEmployee、isEmployee 或 hasRole。这就是在转换为数组时使用roles 的原因。在转换为数组时,您可能需要编写自定义 toArray 方法以从结果集中删除 roles。

【讨论】:

  • 我看到它有效,但它可能不是完整的解决方案。上面的代码应该可以正常工作,并且根本不应该加载您的关系。
  • 好吧,我的 laravel 版本是 4.2.*@dev,我的模型中没有 $appends。我正在用完整的代码更新我的问题。
猜你喜欢
  • 1970-01-01
  • 2015-03-30
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2015-08-24
  • 2019-03-10
相关资源
最近更新 更多