laravel - 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.
解决方案
您已经表明您不想在您的用户模型上使用其他方法,但这是您除了使用已经使用的闭包之外的最佳方法。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();
推荐阅读
- c - EOF 无法识别
- python-3.x - 带有设备型号 ID 和设备 ID 的树莓派分段错误的 Google 助手
- ruby-on-rails - Forest Admin 尚未在生产中显示模型,但在开发中显示它
- python - Anaconda3 的 python 找不到 kerberos 凭证缓存
- python - 重新 - 除 $ 和百分比外的所有数字
- swift - 谷歌地图不允许我定位用户位置?
- java - JAVA中的FOR循环数组,不起作用
- c# - 我如何在 Asp.net mvc 中使用 viewmodel 更新多个表
- apache-spark - 在 Spark 中执行时删除从节点
- php - 在哪里存储带有 cookie 且没有会话的用户的用户 ID(记住我)