================= A simple extension allows to access column values of junction table in ORM way without declaring additional model for that table in many-to-many relation. Extension overwrites \yii\db\ActiveQuery::viaTable() and allows to pass there array of column names of junction table which will be attached to child models as properties.
The preferred way to install this extension is through Composer.
Either run
$ composer require alexinator1/yii2-jta
or add
"alexinator1/yii2-jta": "*"
to the require
section of your composer.json
file.
Just inherit your both model classes related in many-to-many relation from alexinator1\jta\ActiveRecord class.
Consider following scheme
class User extends \alexinator1\jta\ActiveRecord
{
....
}
class Group extends \alexinator1\jta\ActiveRecord
{
....
}
and pass array of attribute names you want to attach to child model to viaTable method
class Group extends \alexinator1\jta\ActiveRecord
{
...
public function getUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('user_group', ['group_id' => 'id'], null, ['role', 'joined_at']);
}
...
}
That's it. Now child model has a property which named as pivot attribute and contains array of corresponding values indexed by parent id. So it can't be accessed following way:
Lazy loading:
$group = Group::findOne($groupId);
foreach($group->users as $user)
{
$role = $user->role[$group->id];
$joinDate = $user->joined_at[$group->id];
...
}
Eager loading:
$group = Group::find()->where($groupId)->with('users')->all();
foreach($group->users as $user)
{
$role = $user->role[$group->id];
$joinDate = $user->joined_at[$group->id];
...
}
Eager loading using 'joinWith' methods:
$groups = Group::find()->joinWith('users')->all();
foreach($groups as $group){
foreach($group->users as $user)
{
$role = $user->role[$group->id];
...
}
}
works with 'array' models as well:
$group = Group::find()
->with('users')
->where($groupId)
->asArray()
->one();
foreach($group['users'] as $user)
{
$role = $user['role'];
$joinDate = $user['joined_at'];
...
}
You may find more code samples in DEMO page. And some unit tests on DEMO page repository
Attached pivot attributes are read-only and acceptable only for models
were populated via relation. They overwrite all other none-declared model properties
(declared via getter or corresponded to table columns)
and are overwritten by declared properties.
If you find any usecases where extension doesn't work properly. Please feel free to issue it or send me to email. We will try to handle it ASAP.
yii2 junction table attributes is released under the MIT License. See the bundled LICENSE.md
for details.
Comments