在 Yii2 中执行原始 SQL 查询?

2022-08-30 10:44:21

当我将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是6个月的时间,我根据另外请注意计算,这是用户获得的每一次胜利,所以它的总和决定了排名。time()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

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


答案 2

推荐