Activerecord And Relations (Pivot Table)


here at the documentation I find a lot of reading data and relations.

I use Pivot tables and everything works fine…

But, how can I change these hasMandy relations in my Pivot Table?

Is there a way to handle this with my Active Record Models or do I need to use SQL Statements here?



what do you want to achieve?

Let’s say I have a User in table “users” and a List of Groups in table “groups”.

My pivot table is "user_groups".

And now I got call call from my site, that I need set a new list of groups for a user…



I solved it this way, but I thought there is a more ActiveRecord approach…

        // first delete all current groups for the user

        $connection->createCommand()->delete('user_groups', 'users_id = '.$user->id)->execute();

        // now save the new groups

        foreach($params['group_list'] as $lId) {

            $data = [

                'users_id' => $user->id,

                'groups_id' => $lId,


            $connection->createCommand()->insert('user_groups', $data)->execute();


So you mean single user can belong to multiple groups? And you want to update that user’s group or insert new (which one)?

If just updating user_group use its AR model, no need to think even in terms of Table.

AFAIK Pivot issues comes only when you do access data via it!