渴望加载时的雄辩关系

时间:2018-08-16 00:52:47

标签: laravel eloquent

在急于加载时,是否有一种别名雄辩关系的方法?例如,我可能有如下查询。

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

但是,如果我还想加载状态为ACTIVE的角色,该怎么办?我能想到的唯一方法是在User模型上复制角色关系,并为其指定一个不同的名称。该查询将类似于以下内容。

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

我可以在用户模型上使用诸如adminRolesactiveRoles之类的方法,但这并不是我想要的,因为有很多可能的参数。

3 个答案:

答案 0 :(得分:2)

您已经表明您不想在用户模型上使用其他方法,但这是除了像已经使用闭包之外最好的方法。通过使诸如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();

答案 1 :(得分:0)

您想要这样吗?

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

使用位置

User::whereHas('roles', function ($query) {
     $query->where('type', ADMIN)->where('status', ACTIVE); 
})->get();

答案 2 :(得分:0)

不幸的是,当 Laravel (8.x) 中当前无法进行预加载时,会出现别名关系。看起来它不会在不久的将来实施,因为 Taylor 已经就此关闭了两个 PR。

https://github.com/laravel/framework/pull/37656#issuecomment-870604176

https://github.com/laravel/framework/pull/31976#issuecomment-599538731

相关问题