2016-07-26 3 views
0

Userモデルは、関係を追跡していますYii2 hasManyのリンクフィールドなし

public function getWorkload() : ActiveQuery 
{ 
    return $this->hasMany(ScheduleWorkload::className(), ['staff_id' => 'id']); 
} 

Findメソッド:

$staffs = User::find() 
      ->alias('u') 
      ->joinWith(['workload as uw' => function($q) { 
       $q->select(['uw.staff_id', 'uw.date', 'uw.time_ranges']); 
      }], true) 
      ->select([ 
       'u.id', 
       'CONCAT(u.first_name, \' \', u.last_name) as name', 
       'u.first_name', 
       'u.last_name', 
       'u.undelivered_messages', 
      ]) 
      ->where(['u.is_staff' => 1]) 
      ->asArray() 
      ->all() 
      ; 

私は、結果セットにuw.staff_idせずにデータを取得する必要がありますか?後処理なしでも可能ですか?

UPDATE:私は、配列のパラメータとして「ワークロード」を必要とするが、後処理を使用して、ちょうど結果セットから「staff_id」を除外しない enter image description here

を持って 結果セット。

生のSQL:

SELECT `u`.`id`, `u`.`undelivered_messages` 
FROM `user` `u` 
LEFT JOIN `schedule_workload` `uw` ON `u`.`id` = `uw`.`staff_id` 
WHERE `u`.`is_staff`=1 
+0

、あなたは今、何の結果セットを持っているのですか?変数 '$ staffs'は' ActiveQuery'型です。 '$ staffs-> createCommand() - > rawSql'の結果は何ですか? – oakymax

+0

私はポストを更新します。更新セクションをご覧ください。 $ staffsは配列です。インクルード - > asArray() - > all() – johndoek

答えて

1

ActiveQueryが参加しました関係のためのネストされた配列を構築するために、ネストされたクエリの結果に外部キーを検索しますので、あなたは、任意の後処理なしでのYiiで行うことはできません。

あなたのための最も便利な方法は、ArrayHelperを使用することです:

$staffs = User::find() 
    ->alias('u') 
    ->joinWith(['workload') 
    ->where(['u.is_staff' => 1]) 
    ->all(); 

return \yii\helpers\ArrayHelper::toArray($staffs, [ 
    User::className() => [ 
     'id', 
     'first_name', 
     'last_name', 
     'name' => function ($user) { 
      return $user->first_name . ' ' . $user->last_name 
     }, 
     'undelivered_messages', 
     'workload', 
    ], 
    ScheduleWorkload::className() => [ 
     'date', 
     'time_ranges', 
     'comment' 
    ] 
], true); 
関連する問題