phpyiisql-order-byyii-cactiverecord

Yii 1.15 CdbCriteria adds up own sorting - magic


It happens that Yii adds ordering by ID to criteria implicitly.

Pay attention to this line in code $criteria->order ='t.id ASC';

My source code:

            $criteria = new CDbCriteria;

            $criteria->select = 't.id, order_id, was_before, became, t.created_at';

            $criteria->addCondition('t.created_at >= \'' . $from . '\'');
            $criteria->addCondition('t.created_at <= \'' . $to . '\'');
            $criteria->alias ='t';


            $criteria->with = [
               'order' => [
                  'select' => 'm.id as b, m.status',
                  'condition' => 'm.status = ' . Order::STATUS_CANCELLED,
                  'alias' => 'm',
                  'with' => [
                     'packerRest' => [
                        
                        'select'=> 'g.id as n',
                        'alias' => 'g'
                     ]
                  ]
               ],
            ];
            
            $criteria->order ='t.id ASC';

Dump of Criteria:

enter image description here

Resulting error:

enter image description here

As you may see I didn't add sorting by ID. Yii does it somehow and breaks the whole query.

I'm already ready to rewrite it in pure MySQL.

Any ideas why it does so?


Solution

  • In Yii it's possible to define the ordering for related models in the model's relations() method via something like: 'packerRest' => [self::HAS_MANY, 'PackerRest', 'order_id', 'order' => 'id DESC' ] which is what turned out to be in your Order model.

    PS: We already figured out the issue in the comments of the question but I'm posting this answer so just we're in the SO format and to make it easier to find and read for others.