Answer the question
In order to leave comments, you need to log in
How to translate SQL using Yii2 ActiveRecord?
Tell me, pliz, how to concisely build such a query using Yii2?
SELECT
slot.logo as `dir`,
room.title as `room`,
meeting.logo as `logo`,
meeting.title as `title`,
meeting.start as `start`,
meeting.end as `end`
FROM
slot, room, meeting
WHERE
slot.screen_id = :screen_id AND
room.id = slot.room_id AND
meeting.room_id = room.id AND
meeting.start < NOW( ) AND
meeting.end > NOW( )
Answer the question
In order to leave comments, you need to log in
If you have all ActiveRecord models with relationships, then something like this:
$results = Slot::find()->select([
'slot.logo as `dir`',
'room.title as `room`',
'meeting.logo as `logo`',
'meeting.title as `title`',
'meeting.start as `start`',
'meeting.end as `end`'
])->joinWith(['meeting', 'room'])->where(
'slot.screen_id = :screen_id AND meeting.start < NOW() AND meeting.end > NOW()',
['screen_id' => $screen_id]
)->all();
Thanks for your reply, Alexey.
The request didn't work for some reason...
I connected the models in this way. Is something wrong?
class Slot extends \yii\db\ActiveRecord {
public function getRoom() {
return $this->hasOne(Room::className(), ['id' => 'room_id']);
}
}
class Room extends \yii\db\ActiveRecord {
public function getMeetings() {
return $this->hasMany(Meeting::className(), ['room_id' => 'id']);
}
}
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'room.title' in 'field list'
The SQL being executed was: SELECT `slot`.logo as `dir`, `room`.title as `room`, `meeting`.logo as `logo`, `meeting`.title as `title`, `meeting`.start as `start`, `meeting`.end as `end` FROM `slot` WHERE slot.screen_id = 1 AND meeting.start < NOW() AND meeting.end > NOW()
Error Info: Array
(
[0] => 42S22
[1] => 1054
[2] => Unknown column 'room.title' in 'field list'
)
Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'room.title' in 'field list'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question