voskobovich / yii2-many-to-many-behavior

This behavior soon will be DEPRECATED. See the link:

Home Page:https://github.com/voskobovich/yii2-linker-behavior

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using string getters / setters with custom junction table values

dtisthammer opened this issue · comments

commented

I'm running into some confusion with using custom getters / setters and a custom junction table value in the same behavior. I need to set a field called 'order_num' with the array index of the corresponding 'team_members' value that is being set from the string setter function:

public function getEmployees() {
    $query = $this->hasMany(Employees::className(), ['employee_id' => 'employee_id'])
                           ->viaTable('departments_teams_assign', ['team_id' => 'team_id']);
    $query->andWhere('status = 1');
    return $query;
}

...

'class' => ManyToManyBehavior::className(),
'relations' => [
    'team_members' => [
        'employees',
            'fields' => [
                'string' => [
                    'get' => function($value) {
                        return implode(',', $value);
                    },
                    'set' => function($value) {
                        return explode(',', $value);
                    },
                ],
            ],
            'viaTableValues' => [
                'order_num' => function() {
                    //need to set as the array index of the above value
                },
        ],
    ],
]

For example - if my input data is a string consisting of the values "56, 25, 14, 108" the corresponding db table values should look like:

team_id employee_id order_num
88 56 1
88 25 2
88 14 3
88 108 4

If feel like there is a fairly simple solution, but I can't seem to figure it out. Please let me know if you can help.

Thank you.

i solved your issue this way

                'class' => \voskobovich\behaviors\ManyToManyBehavior::className(),
                'relations' => [
                    'tag_ids' =>
                        [
                            'tags',
                            'viaTableValues' => [
                                'sortOrder' => function($model, $relationName, $attributeName, $relatedPk) {
                                    return ((int)array_search($relatedPk, $model->tag_ids))+1;
                                },
                            ],
                        ]
                ],
            ],`
commented

Thank you. I came to a similar solution shortly after I posted this.