Loading

关于TP6 用with关联加where条件的神坑

TP6的模型以及模型关联相当好用,但今天遇到了一个神坑,硬是摸索了一小时最终得以解决!

1、User模型

class User extends Model
{
	public function roles()
	{
		return $this->belongsToMany(Role::class,UserRole::class);
	}
}

2、Role模型

class Role extends Model
{
	protected $updateTime = false;
}

3、关联模型

class UserRole extends Pivot
{
	protected $autoWriteTimestamp = true;
}

以上是我定义的模型及关联关系,然后我需要查出所有用户和用户所拥有的角色,如下

User::with('roles')->select();

结果:

image

但用户所拥有的角色中,我只需要管理员角色,因此在关联模型中加上where条件进行查询,如下:

$data = User::with(['roles' => function ($query) {
		$query->where('role_id',10);
	}])->select();

这里最终查询结果是查不到关联的角色信息了,如图:

image

解决:

这里需要加上getQuery()方法,对于这个getQuery方法,官方文档也没有详细说明,最终是在评论区里找到的答案。

$data = User::with(['roles' => function ($query) {
		$query->getQuery()->where('role_id',10);
	}])->select();

于是就得到了我们想要的结果:

image

posted @ 2022-04-21 11:54  木头人4216  阅读(2137)  评论(1编辑  收藏  举报