php 在Yii2中执行原始SQL查询?

8cdiaqws  于 2023-06-04  发布在  PHP
关注(0)|答案(2)|浏览(150)

我写了下面的查询,因为我把我的PHP网站迁移到Yii2框架。我想将它们添加到我的控制器,以便显示赢得的前10名投注。我已经尝试过很多Yii2数据库类,但我不能让它工作。
我的table是:

用户:

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
");
2ic8powd

2ic8powd1#

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

bwntbbo3

bwntbbo32#

如果$sql是用于执行原始选择查询原始查询

$result = \Yii::$app->getDb()->createCommand($sql)->queryAll();

用于执行原始插入/删除/更新查询

$result = \Yii::$app->getDb()->createCommand($sql)->execute();

相关问题