[英]Laravel/Eloquent - Order By a Model's Relationship Without Using Table Names
[英]Errors using Laravel's Eloquent relationship
我有2个模型-User和RoleUser。 每个用户都分配有一个角色。 因此,我通过在User模型上声明“ role”方法来定义一对一关系。
public function role(){
return $this->hasOne('Vanguard\RoleUser', 'user_id');
}
这是我的榜样
class RoleUser extends Model
{
//
public $table = 'role_user';
protected $fillable = ['user_id', 'role_id'];
}
在控制器中,我尝试获取role_id = 2的用户,但查询不断返回所有用户(即3),而不仅仅是一个用户。 这是我的控制器
$users = User::with(['role' => function ($query) {
$query->where('role_id', 2);
}])->get();
请问是什么原因造成的?
与with with
使用作用域只会将该作用域添加到预先加载的关系中,无论它是否存在。 要实现您想要的目标,您还需要执行一个whereHas
。
$users = User::whereHas('role', function ($q) {
$q->where('role_id', 2);
})->with(['role' => function ($q) {
$q->where('role_id', 2);
}])->get();
将查询更改为如下所示:
User::all()->with('role')->where('role_id', 2)->get()
希望对您有所帮助。
假设您已定义:
那么您可以简单地将查询写为:
$role = Role::with('users')->find(2);
$users = $role->users;
上面的示例将为您提供所有角色ID为2的用户。
假设每个用户可能只有一个角色,那么尝试一下:
在您的用户模型中:
class User extends Model
{
public function role()
{
return $this->belongsTo(RoleUser::class);
}
}
在您的RoleUser模型中:
class RoleUser extends Model
{
public function users()
{
return $this->hasMany(User::class);
}
}
现在,获取所需的数据(首先在Tinker中尝试):
// Users with role_id 2
$users = User::where('role_id', 2)->get();
// Eager load the Role model to get the entire Role record for each user
$users = User::with('role')->where('role_id', 2)->get();
// Get role's where role_id is 2, and eager load the users
$role = RoleUser::with('users')->where('id', 2)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.