Skip to content
This repository was archived by the owner on Jan 4, 2020. It is now read-only.
This repository was archived by the owner on Jan 4, 2020. It is now read-only.

withJoin 和 withCount 同时使用时报SQL字段出错 #548

@byoukinn

Description

@byoukinn

使用以下关联查询

HomeworkModel::withJoin([
    'user' =>	['name', 'id'],
    'attachment' => ['name'],
    ], 'LEFT')
->withCount('file')
->selectOrFail();

生成了以下sql

SELECT 
`homework_model`.`id`,
`homework_model`.`title`,
`homework_model`.`desc`,
`user`.`name` AS `user__name`,
`user`.`id` AS `user__id`,
`attachment`.`name` AS `attachment__name`,

(SELECT COUNT(*) AS tp_count 
FROM `hw_file` `count_table` 
WHERE  ( `count_table`.`hid` = hw_homework.id ) LIMIT 1)

AS `file_count` 
FROM `hw_homework` `homework_model` 

LEFT JOIN `hw_user` `user` ON `homework_model`.`uid`=`user`.`id` 
LEFT JOIN `hw_file` `attachment` ON `homework_model`.`attachment_id`=`attachment`.`id` LIMIT 100

报错 1054 - Unknown column 'hw_homework.id' in 'where clause'
原因 在from语句后已重命名hw_homework表为 homework_model
再子查询就会找不到hw_homework
尝试过更换withJoin()位置,没有生效。

使用with()代替withJoin(),但没办法使用查询多个需要关联的模型。

HomeworkModel::with([
    'user' =>	['name', 'id'],
    'attachment' => ['name'],
    ])
->withCount('file')
->selectOrFail();

报错Too few arguments to function think\db\Query::name(), 0 passed and exactly 1 expected
检查sql语句,生成如下

SELECT *,(SELECT COUNT(*) AS tp_count FROM `hw_file` `count_table` WHERE ( `count_table`.`hid` =hw_homework.id ) LIMIT 1) AS `file_count` FROM `hw_homework`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions