Cake\ORM\Association\BelongsToMany::_saveTarget PHP Method

_saveTarget() protected method

Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
protected _saveTarget ( Cake\Datasource\EntityInterface $parentEntity, array | Traversable $entities, array $options ) : Cake\Datasource\EntityInterface | boolean
$parentEntity Cake\Datasource\EntityInterface the source entity containing the target entities to be saved.
$entities array | Traversable list of entities to persist in target table and to link to the parent entity
$options array list of options accepted by `Table::save()`
return Cake\Datasource\EntityInterface | boolean The parent entity after all links have been created if no errors happened, false otherwise
    protected function _saveTarget(EntityInterface $parentEntity, $entities, $options)
    {
        $joinAssociations = false;
        if (!empty($options['associated'][$this->_junctionProperty]['associated'])) {
            $joinAssociations = $options['associated'][$this->_junctionProperty]['associated'];
        }
        unset($options['associated'][$this->_junctionProperty]);
        if (!(is_array($entities) || $entities instanceof Traversable)) {
            $name = $this->property();
            $message = sprintf('Could not save %s, it cannot be traversed', $name);
            throw new InvalidArgumentException($message);
        }
        $table = $this->target();
        $original = $entities;
        $persisted = [];
        foreach ($entities as $k => $entity) {
            if (!$entity instanceof EntityInterface) {
                break;
            }
            if (!empty($options['atomic'])) {
                $entity = clone $entity;
            }
            $saved = $table->save($entity, $options);
            if ($saved) {
                $entities[$k] = $entity;
                $persisted[] = $entity;
                continue;
            }
            // Saving the new linked entity failed, copy errors back into the
            // original entity if applicable and abort.
            if (!empty($options['atomic'])) {
                $original[$k]->errors($entity->errors());
            }
            if (!$saved) {
                return false;
            }
        }
        $options['associated'] = $joinAssociations;
        $success = $this->_saveLinks($parentEntity, $persisted, $options);
        if (!$success && !empty($options['atomic'])) {
            $parentEntity->set($this->property(), $original);
            return false;
        }
        $parentEntity->set($this->property(), $entities);
        return $parentEntity;
    }