【问题标题】:Eager Loading with Eloquent使用 Eloquent 进行热切加载
【发布时间】:2017-06-15 14:33:33
【问题描述】:

我有以下代码:

$users = User::with('profile')->paginate($count);

和:

$roles = Role::withCount('users')->get();

现在使用 laravel-debugbar,当我打开用户页面时,我看到正在执行 107 个查询,使得页面加载非常缓慢,我感觉当我添加更多用户时,执行的查询总数是会增加。我查看了代码,但现在我不知道它有什么问题或如何减少生成的查询数量。

这些是我的模型:

用户.php

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Kodeine\Acl\Traits\HasRole;

class User extends Authenticatable
{
    use HasRole, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

   protected $table = "users";
    protected $appends = ['role'];

   public function profile()
    {
        return $this->hasOne('App\Models\Profile');
    }

   public function getRoleAttribute() {
        return $this->getRoles();
    }
}

Role.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Kodeine\Acl\Traits\HasPermission;
use Cviebrock\EloquentSluggable\Sluggable;

class Role extends Model
{
    use HasPermission, Sluggable;

   protected $table = "roles";

   /**
     * The attributes that are fillable via mass assignment.
     *
     * @var array
     */
    protected $fillable = ['name', 'slug', 'description'];

   /**
     * Roles can belong to many users.
     *
     * @return Model
     */
    public function users()
    {
        return $this->belongsToMany('App\Models\User', 'role_user', 'role_id', 'user_id');
    }

   /**
     * List all permissions
     *
     * @return mixed
     */
    public function getPermissions()
    {
        return $this->getPermissionsInherited();
    }

   /**
     * Checks if the role has the given permission.
     *
     * @param string $permission
     * @param string $operator
     * @param array  $mergePermissions
     * @return bool
     */
    public function can($permission, $operator = null, $mergePermissions = [])
    {
        $operator = is_null($operator) ? $this->parseOperator($permission) : $operator;

       $permission = $this->hasDelimiterToArray($permission);
        $permissions = $this->getPermissions() + $mergePermissions;

       // make permissions to dot notation.
        // create.user, delete.admin etc.
        $permissions = $this->toDotPermissions($permissions);

       // validate permissions array
        if ( is_array($permission) ) {

           if ( ! in_array($operator, ['and', 'or']) ) {
                $e = 'Invalid operator, available operators are "and", "or".';
                throw new \InvalidArgumentException($e);
            }

           $call = 'canWith' . ucwords($operator);

           return $this->$call($permission, $permissions);
        }

       // validate single permission
        return isset($permissions[$permission]) && $permissions[$permission] == true;
    }

   /**
     * @param $permission
     * @param $permissions
     * @return bool
     */
    protected function canWithAnd($permission, $permissions)
    {
        foreach ($permission as $check) {
            if ( ! in_array($check, $permissions) || ! isset($permissions[$check]) || $permissions[$check] != true ) {
                return false;
            }
        }

       return true;
    }

   /**
     * @param $permission
     * @param $permissions
     * @return bool
     */
    protected function canWithOr($permission, $permissions)
    {
        foreach ($permission as $check) {
            if ( in_array($check, $permissions) && isset($permissions[$check]) && $permissions[$check] == true ) {
                return true;
            }
        }

       return false;
    }


   /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'name'
            ]
        ];
    }
}

Profile.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $table = "profiles";

   public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}

这似乎是重复的查询:

select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`created_at` as `pivot_created_at`, `role_user`.`updated_at` as `pivot_updated_at` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '4'

编辑: 问题似乎来自我的角色,我正在查看控制器和模型中的代码,但我不知道出了什么问题。我将$roles = Role::withCount('users')-&gt;get(); 更改为$roles = Role::with('users')-&gt;withCount('users')-&gt;get();,现在生成的查询更少(71 个仍然很多)。

【问题讨论】:

  • 在您看来,您是否在调用任何其他关系?例如角色或角色权限?
  • 是的,我更新了我的帖子。
  • getPermissionsInherited()在哪里?
  • 我正在使用这个包来管理角色github.com/kodeine/laravel-acl,但是我还没有在我的应用程序中实现权限,所以我没有使用那个功能。
  • 不知何故您正在加载UserRole 之间的关系。可能是那个包,尝试禁用它,看看这些查询是否仍然存在。

标签: laravel eloquent laravel-5.4 eager-loading


【解决方案1】:

是用户模型上的 appends 角色属性导致了过多的查询。作为测试注释,附加角色并测试随后运行了多少查询。您可能需要延迟加载角色以尽量减少查询数量。

【讨论】:

  • 我确信问题出在我的控制器上,非常感谢您的帮助,现在似乎工作正常。
  • 很高兴听到它,我遇到了与附加字段类似的问题。关系链很快就会失控。那么,赏金呢;)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
相关资源
最近更新 更多