简体   繁体   中英

How to convert this raw query into ActiveRecord in Yii Framework 2

Below are my database tables

left_table
id    name
1     A
2     B
3     C
4     D
5     E

right_table
id    left_table_id     size      date_time
1     1                 xs        2017-06-13 14:20:00
2     3                 s         2017-06-13 14:25:00
3     2                 xs        2017-06-13 14:27:00
4     1                 s         2017-06-13 14:30:00
5     2                 m         2017-06-13 14:32:00
6     2                 xs        2017-06-13 14:33:00
7     3                 xl        2017-06-13 14:40:00
8     4                 s         2017-06-13 14:41:00
9     4                 m         2017-06-13 14:45:00
10    5                 m         2017-06-13 14:46:00

Below is the raw sql query to get the records of the left_table order by the max(date_time) DESC where date_time <= NOW() as the following result.

SELECT t.id, t.name, r.date_time
FROM left_table AS t
JOIN (
    SELECT id, MAX(date_time) AS date_time
    FROM right_table
    WHERE date_time <= NOW() 
    GROUP BY id 
) AS r ON t.id = r.id
ORDER BY r.date_time DESC;

Result left_table order by max(add_time) DESC

id    name    max(add_time)   
2     B       2017-06-13 14:33:00
1     A       2017-06-13 14:30:00
3     C       2017-06-13 14:25:00

This is because date_time of left_table_id of 4 and 5 is > NOW(). Assume NOW() = 2017-06-13 14::35:00 . Note that left_table_id 3 has one add_time > NOW() but it is still being selected because it has other right record, add_time <= NOW() .

How can I use ActiveRecord or ActiveQuery to get the same result in Yii Framework 2 ? The ActiveRecord or ActiveQuery is meant for Yii GridView with ActiveDataProvider or Pagination with LinkPager

You could use a suquery this way and leftjoin the subquery
(assuming ChildClass and ParentCLass as the related classes in pseudo code a suggestion below)

  $subQuery = ChildClass::find()->select( 'id, MAX(date_time) AS date_time')
                ->having('MAX(date_time) <=now()')
                ->groupBy('id');

  $query = ParentClass::find();
  $query->leftJoin('R' => $subquery, 'R.id = parentTable.id' )
        ->orderBy(['R.date_time'=> SORT_DESC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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