Reputation: 1697
I'm using Yii2's DBSession class to store web application sessions into a database table, called session
.
This table by default only has 3 columns - id
, expire
and data
.
I'd like to store additional information into this table, like the user_id
of a logged in user.
Edit: So there's a parent class called yii\web\MultiFieldSession but no examples about how it's used. I'll see what I can discover...
Upvotes: 4
Views: 5473
Reputation: 550
I didn't want a function in a config file, so I ended up with this:
config/web.php
'components' =>
[
'session' =>
[
'class' => 'app\models\Session',
],
],
models/Session.php
class Session extends \yii\web\DbSession
{
protected function composeFields($id = null, $data = null)
{
$fields = parent::composeFields($id, $data);
$fields['user_id'] = \Yii::$app->user->id;
return $fields;
}
}
Upvotes: 0
Reputation: 1281
create migration:
$this->createTable('session', [
'id' => $this->char(40)->notNull(),
'expire' => $this->integer(),
'data' => $this->binary(),
'user_id' => $this->integer()
]);
$this->addPrimaryKey('session_pk', 'session', 'id');
add this to config:
'components' => [
'session' => [
'class' => 'yii\web\DbSession',
'writeCallback' => function($session){
return [
'user_id' => Yii::$app->user->id
];
}
// 'db' => 'mydb', // the application component ID of the DB connection. Defaults to 'db'.
// 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
],
Upvotes: 10
Reputation: 4160
Check writeCallBack (a callback that will be called during session data writing)
By Using callback you can set your own database fields.. Used by composeField()
Upvotes: 0