[英]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. 下面是原始sql查询,用于通过max(date_time)DESC获取left_table顺序的记录,其中date_time <= NOW()作为以下结果。
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 结果left_table按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(). 这是因为4和5的
left_table_id
的date_time
是> NOW()。 Assume NOW() = 2017-06-13 14::35:00
. 假设
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()
. 请注意,left_table_id 3具有一个
add_time > NOW()
但仍处于选中状态,因为它具有其他右记录,即add_time <= NOW()
。
How can I use ActiveRecord
or ActiveQuery
to get the same result in Yii Framework 2
? 如何使用
ActiveRecord
或ActiveQuery
在Yii Framework 2
获得相同的结果? The ActiveRecord
or ActiveQuery
is meant for Yii GridView
with ActiveDataProvider
or Pagination
with LinkPager
ActiveRecord
或ActiveQuery
适用于具有ActiveDataProvider
Yii GridView
或具有LinkPager
Pagination
You could use a suquery this way and leftjoin the subquery 您可以通过这种方式使用suquery并左联接子查询
(assuming ChildClass and ParentCLass as the related classes in pseudo code a suggestion below) (假设ChildClass和ParentCLass为伪代码中的相关类,以下为建议)
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.