Yii 2.0: yii2-junction-table-attributes

A simple extension allows to access column values of junction table in ORM way without declaring additional model.
2 followers

##Yii2 Junction Table Attributes

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.

Requirements

  • Yii 2.0
  • PHP 5.4

Installation

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.

Usage

Just inherit your both model classes related in many-to-many relation from alexinator1\jta\ActiveRecord class.

Consider following scheme

Database scheme for example

class User extends \alexinator1\jta\ActiveRecord
{
    ....
}
class Team extends \alexinator1\jta\ActiveRecord
{
    ....
}

and pass array of attribute names you want to attach to child model to viaTable method

class Team extends ActiveRecord
{
    ...
 
    public function getMembers()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])
            ->viaTable('user_team', ['team_id' => 'id'], null, ['role', 'joined_at']);
    }
 
    ...
}

That's it. Now you can access these fields as usual properties

$team = Team::findOne($teamId);
    foreach($team->members as $user)
    {
        $role = $user->role;
        $joinDate = $user->joined_at;
        ...
    }

works with 'array' models as well:

team = Team::find()->where($teamId)->asArray()->one();
    foreach($team->members as $user)
    {
        $role = $user['role'];
        $joinDate = $user['joined_at'];
        ...
    }

Note!

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.

License

**yii2 junction table attributes ** is released under the MIT License. See the bundled LICENSE.md for details.

Resources

Total 1 comment

#19771 report it
KRANTHI KUMAR at 2016/02/10 07:02am
getting Error on viaTable()

HI , Thank you very much for your best sharing.

when i am creating relation by using viaTable() then its not working getting team_id property error,

Example

class Team
{
 ... 
 public function getUserTeams()
    {
        return $this->hasMany(UserTeam::className(), ['team_id' => 'id']);
    }
 
public function getUsers()
    {
        return $this->hasMany(UserT::className(), ['id' => 'user_id'])
               // ->viaTable('user_team', ['team_id','id' ])
                ->via('userTeams');
            ;
    }
 
 public function extraFields()
    {
        return [
            'UserTeams' => 'userTeams', //http://127.0.0.1:8080/api/web/team?expand=UserTeams
            'Users' => 'users',  // http://127.0.0.1:8080/api/web/team?expand=UserTeams,Users
        ];
    }
 
...
}
->viaTable('user_team', ['team_id','id' ]) then getting error like 
 
   "name": "Unknown Property",
"message": "Getting unknown property: api\\modules\\v1\\modules\\cosource\\models\\TeamT::team_id",

so i create a relation using via() then its working.

OUTPUT

"items": [
        {
            "id": 1,
            "name": "AA_TEAM",
            "UserTeams": [
                {
                    "user_id": 1,
                    "team_id": 1,
                    "role": "user",
                    "joined_at": "2016-02-10 00:00:00"
                },
                {
                    "user_id": 2,
                    "team_id": 1,
                    "role": "user",
                    "joined_at": "2016-02-10 00:00:00"
                }
            ],
            "Users": [
                {
                    "id": 1,
                    "name": "AAAAA"
                },
                {
                    "id": 2,
                    "name": "BBBBB"
                }
            ]
        },
] ;

Leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet