如何为此MySQL查询创建ActiveRecord查询


How to create ActiveRecord query for this MySQL query?

我得到了MySQL查询,如何用ActiveRecord写这个?

SELECT *
FROM `sel_posts`
WHERE `login_id` = 22 OR 23 OR 24 ... (this ids from array $ifollow)
ORDER BY `datetime` DESC
LIMIT 0 , 20

首先,最好将WHERE部分中的OR替换为IN

假设模型名为SelPost,以下是如何使用ActiveQuery:

$models = SelPost::find()
    ->where(['login_id' => $ifollow])
    ->orderBy(['datetime' => SORT_DESC])
    ->limit(20)
    ->all();

where足够聪明,可以在$ifollow为数组的情况下自动添加in运算符。

官方文档:

  • SQL IN
  • 活动记录
  • ActiveQuery