簡體   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