<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def sync(self, ids, detaching=True):
 """ Sync the intermediate tables with a list of IDs or collection of models """

        changes = {"attached": [], "detached": [], "updated": []}

        if isinstance(ids, Collection):
            ids = ids.model_keys()

        current = self._new_pivot_query().lists(self._other_key).all()

        records = self._format_sync_list(ids)

        detach = [x for x in current if x not in records.keys()]

        if detaching and len(detach) > 0:
            self.detach(detach)

            changes["detached"] = detach

        changes.update(self._attach_new(records, current, False))

        if len(changes["attached"]) or len(changes["updated"]):
            self.touch_if_touching()

        return changes