在 Yii2 中执行原始 SQL 查询?

Performing raw SQL queries in Yii2?

我在将 PHP 网站迁移到 Yii2 框架时编写了以下查询。我想将它们添加到我的控制器中,以显示赢得的前 10 个赌注。我试过很多 Yii2 数据库 类 但我无法让它工作。

我的表是:

用户:

id | user_name | user_status | ...other columns...

投注:

id | user_id | date_time |...other columns...| balance_return

我想在Yii2中得到的查询是:

$query_all = $dbh->query("
    SELECT SUM(bets.balance_return) AS total_win
         , bets.user_id
         , users.user_name
         , users.user_status
      FROM bets INNER JOIN users ON bets.user_id = users.id
     WHERE users.user_status = 'verified'
       AND bets.date_time > " . $start_date . "
  GROUP BY bets.user_id
  ORDER BY total_win DESC
");

变量start_date是我根据time()计算的6个月的时间段另外请注意balance_return是用户获得的每一次胜利所以它的总和决定了排名。

第二个查询是:

$qwi = $dbh->query("
    SELECT SUM(bets.balance_return) AS total_win
         , bets.user_id
         , users.user_name
         , users.user_status
      FROM bets INNER JOIN users ON bets.user_id = users.id
     WHERE users.user_status = 'verified'
       AND bets.date_time > " . $start_date . "
  GROUP BY bets.user_id
  ORDER BY total_win DESC LIMIT 0,10
");

你可以像这样执行原始 sql

$connection = Yii::$app->getDb();
$command = $connection->createCommand("
    SELECT SUM(bets.balance_return) AS total_win
     , bets.user_id
     , users.user_name
     , users.user_status
    FROM bets INNER JOIN users ON bets.user_id = users.id
    WHERE users.user_status = 'verified'
    AND bets.date_time > :start_date
    GROUP BY bets.user_id
    ORDER BY total_win DESC", [':start_date' => '1970-01-01']);

$result = $command->queryAll();

我推荐阅读:http://www.yiiframework.com/doc-2.0/yii-db-connection.html#createCommand()-detail

第一个参数是 sql(带占位符),第二部分是要与占位符一起使用的值数组。