繁体   English   中英

Yii再向CDbCriteria添加一个选择

[英]Yii add one more select to CDbCriteria

我对Yii比较陌生。

我对原始SQL有信心,但在ORM方面仍然有点迷失。 所以这可能是一个虚假的问题。

我已经检索了构建此类CDbCriteria所有必要记录:

$criteria = new CDbCriteria(array(
  'select' => 'sum(items) as items',
  // 'condition' => 't.items > 0 and order.storage = "'Product::STORAGE_LOCAL . '"',

  'condition' => 't.items > 0 and order.storage = "' .  Product::STORAGE_LOCAL . '"',
  'order' => 'sum(items) DESC',
  'with' => array(
    'product' => array(
       'select' => 'code, title, producer, local_rest',

        **// 'select' => 'code, title, producer, sum(local_rest) as   local_rest',**
       'group' => 'product.code',
    )
  ),

  'join' => 'inner join `order` `order` on `t`.`order_id` = `order`.`id`',
   // 'group' => '`product`.`code`, `product`.`title`',
   'group' => '`product`.`code`',
   'together' => true
));

我试图得到的总和local_rest领域做group by 不幸的是,它不会返回它应该是什么。

这就是我尝试将其构建到CDbCriteria

// 'select' => 'code, title, producer, sum(local_rest) as local_rest', - 没运气。

我可以使用分离查询得到它:

$sum_local_rest = Yii::app()->db->createCommand("
  SELECT  id,code, title, sum(local_rest) as sum_rest FROM product GROUP BY code
  ORDER BY `sum_rest`  DESC
");

还有一点需要注意 - 产品表中有重复的记录。 即我们有不止一次的同一产品。 但是,如果我使用GROUP BY它有助于划分这个缺点。 这是由于糟糕的数据库设计,应该在将来修复。

问题是我需要以某种方式将它与CDbCriteria绑定,因为它由CDataProviderCDataProvider使用,由GridView

如何在一个CDbCriteria连接这两个问题的任何提示?

提前致谢

编辑

看看目前的答案,我觉得我需要总结一下。 主要问题是我需要告诉CDbCriteria检索记录(由HAS_Many连接绑定)并计算所有这些记录的SUM并使CDbCriteria执行这些记录的GROUP BY。 没有其它的方法。 我不能明确地这样做。 因为我将CDbCriteria传递给CDataProvider ,它应该运行查询。 这就是Yii的工作方式(据我所知)。

 //You can merge your criteria like here: $criteria = new CDbCriteria(); //First criteria $criteria_2 = new CDbCriteria(); //Second criteria $criteria->mergeWith($criteria_2); //Merge criteria and criteria_2 SomeModel::model()->findAll($criteria); //Find by criteria 

我不明白为什么这样的事情不起作用:

$criteria = new CDbCriteria; $criteria->select = array( "SUM(t.items) as items", "SUM(product.local_rest) as product_local_rest" ); $criteria->condition = "t.items > 0 and order.storage = "' . Product::STORAGE_LOCAL . '"'; $criteria->join = 'inner join `order` `order` on `t`.`order_id` = `order`.`id`'; $criteria->with = "product"; $criteria->group = "product.code"; $criteria->together = true;

由于您将together设置为true,因此您的关系列应该可用于您的查询,并按关系的名称(产品)别名。 (注意:要在CActiveDataProvider返回的模型上访问SUM(product.local_rest)的结果,您需要将$product_local_rest设置$product_local_rest返回模型的类的公共属性。)

或者,如果您更乐于编写原始SQL,则可以使用CDbCommand生成结果数组,然后使用CArrayDataProvider而不是CActiveDataProvider。 http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider

您也不必将所有元素都传递给条件。 尝试将标准拆分为更多代码,如下所示:

 $criteria = new CDbCriteria();
 $criteria->select = 'sum(items) as items, ' . Product::STORAGE_LOCAL;
 $criteria->condition = 't.items > 0 and order.storage = ' .  Product::STORAGE_LOCAL;

//etc.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM