Here’s how to see the native SQL or raw SQL generated by Yii queries. The easy way is to open the debug area and click on the DB tab.
Recently, I was debugging complex SQL queries for background tasks and wanted to see the raw SQL generated. The debugger isn’t as easily available.
I used the approach:
$query->createCommand()->getRawSql()
In this example, I’m debugging a complex left outer join query:
$query = (new Query()) ->select(['participant.participant_id']) ->from('participant') ->join('LEFT OUTER JOIN', 'meeting_log', 'participant.meeting_id=meeting_log.meeting_id') ->where(['participant.participant_id'=>'meeting_log.actor_id']) ->andWhere(['participant.meeting_id'=>$item->meeting_id]) ->andWhere('meeting_log.action<>'.MeetingLog::ACTION_OPEN_MEETING) ->distinct(); var_dump($query->createCommand()->getRawSql());
The output is shown in raw or native SQL:
string(271) "SELECT DISTINCT `participant`.`participant_id` FROM `participant` LEFT OUTER JOIN `meeting_log` ON participant.meeting_id=meeting_log.meeting_id WHERE (`participant`.`participant_id`='meeting_log.actor_id') AND (`participant`.`meeting_id`=326) AND (meeting_log.action<>5)"