protected function _saveLinks(EntityInterface $sourceEntity, $targetEntities, $options)
    {
        $target = $this->getTarget();
        $junction = $this->junction();
        $entityClass = $junction->getEntityClass();
        $belongsTo = $junction->getAssociation($target->getAlias());
        $foreignKey = (array)$this->getForeignKey();
        $assocForeignKey = (array)$belongsTo->getForeignKey();
        $targetPrimaryKey = (array)$target->getPrimaryKey();
        $bindingKey = (array)$this->getBindingKey();
        $jointProperty = $this->_junctionProperty;
        $junctionRegistryAlias = $junction->getRegistryAlias();

        foreach ($targetEntities as $e) {
            $joint = $e->get($jointProperty);
            if (!$joint || !($joint instanceof EntityInterface)) {
                $joint = new $entityClass([], ['markNew' => true, 'source' => $junctionRegistryAlias]);
            }
            $sourceKeys = array_combine($foreignKey, $sourceEntity->extract($bindingKey));
            $targetKeys = array_combine($assocForeignKey, $e->extract($targetPrimaryKey));

            $changedKeys = (
                $sourceKeys !== $joint->extract($foreignKey) ||
                $targetKeys !== $joint->extract($assocForeignKey)
            );
            // Keys were changed, the junction table record _could_ be
            // new. By clearing the primary key values, and marking the entity
            // as new, we let save() sort out whether or not we have a new link
            // or if we are updating an existing link.
            if ($changedKeys) {
                $joint->isNew(true);
                $joint->unsetProperty($junction->getPrimaryKey())
                    ->set(array_merge($sourceKeys, $targetKeys), ['guard' => false]);
            }
            $saved = $junction->save($joint, $options);

            if (!$saved && !empty($options['atomic'])) {
                return false;
            }

            $e->set($jointProperty, $joint);
            $e->setDirty($jointProperty, false);
        }

        return true;
    }