在Yii2中执行原始SQL查询?

时间:2015-05-06 15:49:58

标签: php mysql yii2 yii2-advanced-app

我将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
");

1 个答案:

答案 0 :(得分:69)

您可以像这样执行原始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(带占位符),第二个参数是要与占位符一起使用的值数组。