首页 > 解决方案 > Alias an Eloquent relationship when eager loading

问题描述

Is there a way to alias a Eloquent relationship when eager loading? For example, I might have a query such as the following.

User::with(['roles' => function ($query) { $query->where('type', ADMIN); }]);

But what if I also want to eager load roles with a status of ACTIVE? The only way I can think of doing it is to duplicate the roles relationship on the User model and give it a different name. The query would then look something like the following.

User::with([
  'roles' => function ($query) { $query->where('type', ADMIN); },
  'otherRoles' => function ($query) { $query->where('status', ACTIVE) }]
);

I could have methods such as adminRoles and activeRoles on my user model, but that's really not what I am looking for as there are so many possible parameters.

标签: laraveleloquent

解决方案


您已经表明您不想在您的用户模型上使用其他方法,但这是您除了使用已经使用的闭包之外的最佳方法。adminRoles您可以通过使用新方法(例如利用现有关系方法)以及相关模型提供的范围来稍微改进代码。

class User extends Eloquent 
{
    public function roles()
    {
        return $this->hasMany(Role::class);
    }

    public function adminRoles()
    {
        return $this->roles()->admin();
    }
}

然后定义要在Role模型上使用的范围。

class Role extends Eloquent
{
    public function scopeAdmin($query)
    {
        $query->where('type', static::ADMIN);
    }
}

您现在可以急切地加载这些作用域关系。

User::with('adminRoles')->get();

推荐阅读