Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复直接使用count(model.*)在mariadb中会报错的问题。 #644

Open
wants to merge 1 commit into
base: 3.0
Choose a base branch
from

Conversation

rentoumu
Copy link

具体问题:

withCount拼接的sql语句为count(model_name.*),然而mariadb、mysql不支持count(table.*)语法,导致报错,仅postgresql能够正常执行。

例如:

$organizations = OrganizationModel::with(['creator'])->withCount(['users'])->where('uid', '=', $this->auth->uid)->page($page)->limit($size)->select()->toArray();

think-orm最终生成sql为:

SELECT
  *,(
    SELECT
      COUNT(
      `user_model`.*) AS think_count         // <---***ERROR***
    FROM
      `user` `user_model`
      INNER JOIN `organization_user` ON `organization_user`.`userId` = `user_model`.`uid`
      INNER JOIN `organization` ON `organization`.`id` = `organization_user`.`organizationId` 
    WHERE
      ( ( `organization_user`.`organizationId` = organization.id ) ) 
      AND `user_model`.`deleteTime` IS NULL 
  ) AS `AAA` 
FROM
  `organization` 
WHERE
  `organization`.`deleteTime` IS NULL

各测试用例

mariadb 10.2测试结果不通过:

image

mysql 5.7 8.0均测试不通过:

image

postgresql 16测试通过:

image

@liu21st
Copy link
Member

liu21st commented Oct 22, 2024

修改关联类的getRelationCountQuery方法的$aggregate($field);为$aggregate($this->localKey);就行了 可以测试下

@rentoumu
Copy link
Author

@liu21st
经过测试,可以解决问题,请问后续会直接在框架内修复吗?
我这里还有个问题,在用alias定义别名后,没有作用于子查询中,导致count出的数据有误,在这里顺便提一下。

//出问题的SQL。
$organizations = OrganizationModel::alias('ooo')->with(['creator'])->withCount(['users'=>'usersCount'])->where('uid', '=', $this->auth->uid)->page($page)->limit($size)->select()->toArray();

// 定义的远程一对多。
$this->hasManyThrough(UserModel::class, OrganizationUserModel::class, 'organizationId', 'uid', 'id', 'userId');
SELECT
  *,(
    SELECT
      COUNT( `id` ) AS think_count 
    FROM
      `user` `user_model`
      INNER JOIN `organization_user` ON `organization_user`.`userId` = `user_model`.`uid`
      INNER JOIN `organization` ON `organization`.`id` = `organization_user`.`organizationId` 
    WHERE
      ( ( `organization_user`.`organizationId` = organization.id ) )  //  <---【ERROR】
      AND `user_model`.`deleteTime` IS NULL 
  ) AS `usersCount` 
FROM
  `organization` `ooo` 
WHERE
  ( `uid` = 4 ) 
  AND `ooo`.`deleteTime` IS NULL 
  LIMIT 0,
  10

image

@liu21st
Copy link
Member

liu21st commented Oct 29, 2024

别名的问题 我改进了下 现在可以测试下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants