yii2 icon indicating copy to clipboard operation
yii2 copied to clipboard

Count query with group in class extends \yii\db\Query

Open sallfris opened this issue 1 year ago • 9 comments

What steps will reproduce the problem?

  1. Create class QueryMyDb extends \yii\db\Query
  2. Modify function in QueryModified
    public function createCommand($db = null)
    {
        if ($db === null) {
            $db = Yii::$app->get('myDb');
        }
        return parent::createCommand($db);
    }
  1. Execute request
(new QueryMyDb())->from('table')
            ->groupBy('column')
            ->count();

What is the expected result?

Query to myDb

What do you get instead?

Query to db

Additional info

Problem this If use (new static()), the query will be correct

Q A
Yii version 2.0.47
PHP version 7.2
Operating system unix

sallfris avatar Mar 17 '23 14:03 sallfris

What's your ../config/main.php section for databases ?

lubosdz avatar Mar 17 '23 16:03 lubosdz

What's your ../config/main.php section for databases ?

The configuration is not relevant. The problem is that Query#queryScalar() create a instance with new self(), ignoring the request initiated from the modified class.

kamarton avatar Mar 18 '23 11:03 kamarton

I solved this some time ago by class SwitchableConnection extends \yii\db\Connection, but it was quite complicated. I like suggested solution in PR - points out nicely the difference static vs self, though I am curious about tests. Current failure does not seem related to this PR, but to Generators support in JSON helper #19766.

lubosdz avatar Mar 18 '23 18:03 lubosdz

@lubosdz Current failure does not seem related to this PR, but to Generators support in JSON helper

I ran in the same issue. I've created a PR to fix the unit test (https://github.com/yiisoft/yii2/pull/19798).

rhertogh avatar Mar 29 '23 15:03 rhertogh

@rhertogh, @bizley is there something to do for this one besides unit test fix that was done?

samdark avatar May 16 '24 09:05 samdark

I think we should changed the mentioned call to static (instead of self).

bizley avatar May 16 '24 10:05 bizley

OK. @bizley do you have time for a pull request? I plan to release soon.

samdark avatar May 16 '24 11:05 samdark

https://github.com/yiisoft/yii2/pull/17346#issuecomment-532758630

rob006 avatar May 16 '24 13:05 rob006

Ech, right. Not sure what to do then.

bizley avatar May 16 '24 14:05 bizley