How to get `extraColumns`?

BaseActiveRecord::link has extraColumns parameter that adds additional column values to be saved in junction table. The question is how to get them back with related models?

You need to use the relation to the junction table itself, since the additional column is on it.

A =---< B >--= C

  A has many B, C has many B

  A has many C via B

If you want to access an additional column on B, you have to use "A has many B" relation.

So where do extraColumns fit in this approach? Do I understand correct that B in your schema is a model? In this case if I make a model for my junction table, I don’t need extraColumns anymore.

Yeah, you are right. We can do our job without using ‘extraColumns’ feature. But it may help reduce some lines of code.

$user = User::findOne($user_id);

$group = Group::findOne($group_id);

$ug = new UserGroup();

$ug->user_id = $user->id;

$ug->group_id = $group->id;

$ug->joined_date = date();


$user = User::findOne($user_id);

$group = Group::findOne($group_id);

$user->link('groups', $group, ['joined_date' => date()]);

Anyway, we need UserGroup model to access ‘joined_date’ attribute.

foreach($user->userGroups as $ug) {

    $groupName = $ug->group->name;

    $joinedDate = $ug->joined_date;


Ok, I get it. Thank you for detailed answer!