Performing raw SQL queries in Yii2?

Solution 1:

You can execute raw sql like this

$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();

I recommend reading: http://www.yiiframework.com/doc-2.0/yii-db-connection.html#createCommand()-detail

The first parameter is the sql (with placeholder(s)) and the second part is an array of values to be used with the placeholders.