關於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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM