Hi guys,
I didn’t find a way to access values from additional columns(apart from keys) of junction table using
ActiveRecord. And I haven’t find similar issue, if I missed it, please point me.
So what I can suggest is: what if we add additional input param to viaTable function which will specify columns of pivot table should be attached and populated as properties of child models.
Database structure:
CREATE TABLE `user` (
`id` INT NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `room` (
`id` INT NOT NULL,
`title` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `user_room` (
`user_id` INT NOT NULL,
`room_id` INT NOT NULL,
`user_role` VARCHAR(45) NULL,
`entered_at` VARCHAR(45) NULL,
..... keys, constraits .....
ENGINE = InnoDB;
So we can have something like this:
class Room extends ActiveRecord
{
...
public function getMembers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('user_room', ['room_id' => 'id'], function(){}, ['user_role', 'entered_at'] );
}
}
class User extends ActiveRecord
{
public $user_role;
public $entered_at;
.......
}
So when we call
$users = $room->members;
We’ll get :
// $users
[
0 => [
'id' => 1
'name'=>'John',
...
'user_role' => 'Admin',
'entered_at' => '2015-07-07 15:40'
],
1 => [
'id' => 2
'name'=>'Jimm',
...
'user_role' => 'Regular',
'entered_at' => '2015-08-08 12:30'
],
....
]
So what do you think about it guys?
Do that make sense?