I want to set default timezone when connection to DB. In Yii1 I use:
'initSQLs'=>["SET time_zone = '+00:00"]
But in Yii2 this property doesn't exist. How I should set default timezone with Yii2?
you can subscribe to event https://github.com/yiisoft/yii2/blob/master/framework/yii/db/Connection.php#L111
I suspect that code should be like this:
Event::on(\yii\db\Connection::className(), \yii\db\Connection::EVENT_AFTER_OPEN, function ($event) {
$event->sender->createCommand("SET time_zone = '+00:00'")->execute();
});
But I can't imagine where I should use them (index.php, config/params.php or anywhere else).
no, this is not class-level event, so it would be like this:
Yii::$app->db->on(\yii\db\Connection::EVENT_AFTER_OPEN, function ($event) {
$event->sender->createCommand("SET time_zone = '+00:00'")->execute();
});
But I can't imagine where I should use them (index.php, config/params.php or anywhere else).
yes, to be true me too. lets wait others.
I found more properly approach (because it should be depends on the timezone app):
Yii::$app->db->on(\yii\db\Connection::EVENT_AFTER_OPEN, function ($event) {
$diffGMT = date('P');
$event->sender->createCommand("SET time_zone = '{$diffGMT}'")->execute();
});
You can do this in config for the db component:
'on afterOpen' => function() ...
Thank you!
For Yii1 my db config was:
'initSQLs'=>array("SET time_zone = '".date('P')."'")}
for Yii2:
'on afterOpen' => function($event) {
$event->sender->createCommand("SET time_zone = '".date('P')."'")->execute();
}
Maybe we should set a timezone after the connection in framework. How do you think?
Added it to docs. Should be enough to find it if needed. Thanks for raising the issue.
Most helpful comment
Thank you!
For Yii1 my db config was:
for Yii2:
Maybe we should set a timezone after the connection in framework. How do you think?