模型关联查询问题
业务逻辑 -实现结果统计每个中心里有几个房间 并且作出条件筛选
##目标sql语句
中心表core 房间表 room branchId 关联ID
SELECT a.*,(
SELECT COUNT(*) FROM room b where b.branchId = a.branchId
) roomNumber
FROM core a HAVING roomNumber >= 2(房间数量);
laravel代码
目前通过手册已经关联了模型 但是找不到生成上方sql语句的方法
关联模型代码 中心模型中 core
public function getBatchRoom()
{
return $this->hasOne(RoomDaoImpl::class,'branchId','branchId');
}
查询代码
$testData = $this->getCoreDao()->with(
['getBatchRoom' => function ($query) {
return $query->count('*');}
])->get()->toArray();
传入id 1 此时日志中生成的sql语句为
select * from `room` where `room`.`branchId` in ('1')
个人理解为此时两张表已经产生了关联 但是并没有生成我想要的sql语句
推荐文章: