如何在yii2搜索模型中实现sql查询?

时间:2017-05-24 11:04:58

标签: yii2 yii2-advanced-app

我有以下查询:

      SELECT hs.*FROM hire_screening hs 
      INNER JOIN (SELECT resume_id,MAX(created_date) AS MaxDateTime 
      FROM hire_screening GROUP BY resume_id) hire_screening 
      ON hs.resume_id = hire_screening.resume_id 
      AND hs.created_date = hire_screening.MaxDateTime

我试过了:

   $query = HireScreening::find()
           ->select(["hs.resume_id","MAX(hs.created_date) AS MaxDateTime"])
           ->innerJoin('hire_screening as hs','hs.resume_id = hire_screening.resume_id')

          ->where(['hire_screening.created_date' => 'MaxDateTime'])
          ->orderBy(['(hs.created_date)' => SORT_DESC])
          ->groupBy(['hs.resume_id']);

当我使用group by结果时,按照存储在表中的顺序显示每个'resume_id'的第一个值。根据created_date,我只需要最新的不同resume_id。 如何在yii2搜索模型中实现此查询?请帮忙。

1 个答案:

答案 0 :(得分:1)

如果要执行原始sql查询方式,则可以使用 createCommand函数。但是它将返回数组,所以在网格中你应该使用数组数据提供程序。

$array= Yii::$app->db->createCommand("
      SELECT hs.*FROM hire_screening hs 
      INNER JOIN (SELECT resume_id,MAX(created_date) AS MaxDateTime 
      FROM hire_screening GROUP BY resume_id) hire_screening 
      ON hs.resume_id = hire_screening.resume_id 
      AND hs.created_date = hire_screening.MaxDateTime")->queryAll();