I have a record for an entity my plugin needs and that may be related to many Entries, so I have a pivot table, much like Craft's usergroups_user table.

I'm creating and updating my table fine and I'm not looking at my pivot table. I notice the the user group approach is to delete any entries before creating new ones:

public function assignUserToGroups($userId, $groupIds = null)
        ->delete('usergroups_users', array('userId' => $userId));

    if ($groupIds)
        if (!is_array($groupIds))
            $groupIds = array($groupIds);

        foreach ($groupIds as $groupId)
            $values[] = array($groupId, $userId);

        craft()->db->createCommand()->insertAll('usergroups_users', array('groupId', 'userId'), $values);

    return true;

I take it this is the best way to handle pivot tables and there is no 'sync' functionality similar to that found on Laravel's Eloquent class http://laravel.com/docs/5.1/eloquent-relationships?

1 Answer 1


There isn't an explicit sync command, but Yii does support MANY_MANY relationships through Active Record and will keep the data in the join table up-to-update automatically if you stick purely with Active Record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.