【问题标题】:How to execute a select and count in one query in Yii如何在 Yii 的一个查询中执行选择和计数
【发布时间】:2019-02-06 04:28:25
【问题描述】:

我想在 Yii 中执行这个 SQL 查询:

select count(id), userID from tableName where type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01' group by userID

有什么方法可以在 findAll()countAll() 或其他 Yii 方法中运行此查询?我不想使用findAllBySQL()

【问题讨论】:

    标签: php sql yii


    【解决方案1】:

    您可以使用以下解决方案在一个语句中执行选择和计数:

    $model=Model::find()->where([your conditions])->count();
    

    【讨论】:

      【解决方案2】:

      Yii 1.1

      $data = MyModel::model()->findAll([
          'select' => [
              'count(id) as count', 
              'userID'
          ],
          'condition' => "type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01'",
          'group' => 'userID',
      ]);
      

      您还需要将count 属性添加到MyModel

      class MyModel extends CActiveRecord {
      
          public $count;
      
          // ...
      }
      

      然后您可以将计数映射到 ID:

      $counts = CHtml::listData($data, 'userId', 'count');
      

      或者在foreach中访问:

      foreach ($data as $model) {
          echo "$model->userID - $model->count\n";
      }
      

      Yii 2

      $data = Post::find()
          ->select([
              'count(id) as count',
              'userID',
          ])
          ->where("type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01'")
          ->groupBy('userID')
          ->asArray()
          ->all();
      

      映射:

      $counts = ArrayHelper::map($data, 'userID', 'count');
      

      Foreach:

      foreach ($data as $row) {
          echo "{$row['userID']} - {$row['count']}\n";
      }
      

      【讨论】:

        猜你喜欢
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多