Yii 1.15 CdbCriteria加上自己的排序 - 魔术

时间:2021-09-23 22:48:11

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

事实上,Yii隐式地通过ID向标准添加排序。

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

请注意代码$ 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:

标准转储:

Yii 1.15 CdbCriteria加上自己的排序 - 魔术

Resulting error:

结果错误:

Yii 1.15 CdbCriteria加上自己的排序 - 魔术

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

正如您所看到的,我没有按ID添加排序。 Yii以某种方式做到并打破了整个查询。

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

我已经准备好在纯MySQL中重写它了。

Any ideas why it does so?

任何想法为什么会这样做?

1 个解决方案

#1


1  

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.

在Yii中,可以通过类似以下内容定义模型的relations()方法中相关模型的排序:'packerRest'=> [self :: HAS_MANY,'PackerRest','order_id','order'=>'id DESC' ]这是订单模型中的结果。

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.

PS:我们已经在问题的评论中找到了问题,但我发布了这个答案,所以我们只是采用SO格式,以便更容易找到并阅读其他人。

#1


1  

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.

在Yii中,可以通过类似以下内容定义模型的relations()方法中相关模型的排序:'packerRest'=> [self :: HAS_MANY,'PackerRest','order_id','order'=>'id DESC' ]这是订单模型中的结果。

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.

PS:我们已经在问题的评论中找到了问题,但我发布了这个答案,所以我们只是采用SO格式,以便更容易找到并阅读其他人。