繁体   English   中英

如何在 Yii2 活动记录中的关系上获取 DISTINCT 行

[英]How to get DISTINCT rows on a relation in Yii2 Active record

我有一个 AieDetail model 如下:

  class AieDetail extends \yii\db\ActiveRecord
  {
      public function getDepts()
      {
          return $this->hasOne(Department::className(), ['DEPT_CODE' => 'DEPT_CODE']);
      }
  }

我有这个查询,我想用于 select distinct COL_ABBREV 列在 Department 表

  $aie_detail = AieDetail::find()->alias('AD')
                        ->select(['DEPT.COL_ABBREV'])
                        ->joinWith(['depts DEPT'])
                        ->where(['not',['DEPT.COL_ABBREV' => ['CA']]])
                        ->distinct()
                        ->all();
    return $aie_detail;

$aie_detail的值是查询而不是数据数组。 获取行的正确方法是什么?

  $aie_detail = AieDetail::find()
                        ->select([Department::tableName() . '.COL_ABBREV'])
                        ->joinWith('depts')
                        ->where([
                          '!=',
                          Department::tableName() . '.COL_ABBREV',
                         'CA'
                        ])
                        ->distinct()
                        ->asArray()
                        ->all();

如果您遇到任何未定义的索引错误,请包括在与 select 语句的关系中使用的外键,或者使用 leftJoin() 方法而不是 joinWith()。

如果你想 select 更多数据和基于单列的不同,然后添加 groupBy() 与 arguments 具有不同的列

$aie_detail = AieDetail::find()->alias('AD')
    ->select('Department.COL_ABBREV')
    ->joinWith(['depts'])
    ->where(['not','Department.COL_ABBREV', 'CA'])
    ->distinct()
    ->all();

使用 '.' 时必须传入实际的表名。 运算符在查询中选择列。

暂无
暂无

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

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