SyncWithoutDetaching

@param $id
@param $relation
@param $attributes
@return mixed
773491
public function syncWithoutDetaching($id, $relation, $attributes)
    {
        return $this->sync($id, $relation, $attributes, false);
    }
1041532
public function store( $id, $data, $attributes = array() )
    {
        $this->forceStoreRegistry = true;
        $storeResult = parent::store( $id, $data, $attributes );

        // Update clustered expiry timestamp
        $expiryTime = time() + $this->properties['options']['ttl'];
        $this->expiryHandler->setTimestamp( ezpRestRouter::ROUTE_CACHE_KEY, $expiryTime );

        return $storeResult;
    }
21109
public function updateExistingPivot($id, array $attributes, $touch = true)
    {
        if ($this->using && empty($this->pivotWheres) && empty($this->pivotWhereIns)) {
            return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch);
        }

        if (in_array($this->updatedAt(), $this->pivotColumns)) {
            $attributes = $this->addTimestampsToAttachment($attributes, true);
        }

        $updated = $this->newPivotStatementForId($this->parseId($id))->update(
            $this->castAttributes($attributes)
        );

        if ($touch) {
            $this->touchIfTouching();
        }

        return $updated;
    }
1343722
protected function postHandler($className, $id, $relation)
    {
        if ($id) {
            if (!$relation) {
                $this->response->setStatusCode(409);
                return 'Conflict';
            }

            $obj = DataObject::get_by_id($className, $id);
            if (!$obj) {
                return $this->notFound();
            }

            $reqFormatter = $this->getRequestDataFormatter($className);
            if (!$reqFormatter) {
                return $this->unsupportedMediaType();
            }

            $relation = $reqFormatter->getRealFieldName($className, $relation);

            if (!$obj->hasMethod($relation)) {
                return $this->notFound();
            }

            if (!Config::inst()->get($className, 'allowed_actions') ||
                !in_array($relation, Config::inst()->get($className, 'allowed_actions'))) {
                return $this->permissionFailure();
            }

            $obj->$relation();

            $this->getResponse()->setStatusCode(204); // No Content
            return true;
        }

        if (!singleton($className)->canCreate($this->getMember())) {
            return $this->permissionFailure();
        }

        $obj = Injector::inst()->create($className);

        $reqFormatter = $this->getRequestDataFormatter($className);
        if (!$reqFormatter) {
            return $this->unsupportedMediaType();
        }

        $responseFormatter = $this->getResponseDataFormatter($className);

        try {
            /** @var DataObject|string $obj */
            $obj = $this->updateDataObject($obj, $reqFormatter);
        } catch (ValidationException $e) {
            return $this->validationFailure($responseFormatter, $e->getResult());
        }

        if (is_string($obj)) {
            return $obj;
        }

        $this->getResponse()->setStatusCode(201); // Created
        $this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());

        // Append the default extension for the output format to the Location header
        // or else we'll use the default (XML)
        $types = $responseFormatter->supportedExtensions();
        $type = '';
        if (count($types)) {
            $type = ".{$types[0]}";
        }

        // Deviate slightly from the spec: Helps datamodel API access restrict
        // to consulting just canCreate(), not canView() as a result of the additional
        // "Location" header.
        if ($this->config()->get('location_header_on_create')) {
            $urlSafeClassName = $this->sanitiseClassName(get_class($obj));
            $apiBase = $this->config()->api_base;
            $objHref = Director::absoluteURL($apiBase . "$urlSafeClassName/$obj->ID" . $type);
            $this->getResponse()->addHeader('Location', $objHref);
        }

        return $responseFormatter->convertDataObject($obj);
    }
1310160
public static function patch($id, $attributes)
    {
        static::invalidateCache($id);

        return \Phramework\Database\Operations\Update::update(
            $id,
            (array) $attributes,
            (
                static::getSchema() === null
                ? static::getTable()
                : [
                    'table' => static::getTable(),
                    'schema' => static::getSchema()
                ]
            ),
            static::getIdAttribute()
        );
    }
269726
public function initialize($attributes, $id = null)
    {
        if ($this->started) {
            return $this;
        }
        
        $this->id = $id ?: $this->id;
        $this->attributes = $attributes;
        $this->started = true;
        
        return $this;
    }
325575
protected function parseForCommonValues($relation)
    {
        if (!$this->hasAttribute($relation)) {
            // If no attribute exists for this relationships
            // we'll make it a simple empty array. This will
            // save us from constantly checking for the attributes
            // actual existence.
            $this->relationships[$relation] = [];

            return false;
        }

        $value = $this->getRelationshipValue($relation);

        if (is_null($value)) {
            $this->relationships[$relation] = [];

            // If the relationship's content is the null value
            // and the Entity's exist in DB, we'll interpret this
            // as the need to detach all related Entities,
            // therefore a sync operation is needed.
            $this->needSync[] = $relation;

            return false;
        }

        return $value;
    }
1227423
protected function updatePivotIfDirty(string $pivotHash, string $relation)
    {
        $aggregate = $this->getRelatedAggregateFromHash($pivotHash, $relation);

        if ($aggregate->hasAttribute('pivot')) {
            $pivot = $aggregate->getEntityAttribute('pivot')->getEntityAttributes();

            $cachedPivotAttributes = $this->getPivotAttributesFromCache($pivotHash, $relation);

            $actualPivotAttributes = array_only($pivot, array_keys($cachedPivotAttributes));

            $dirty = $this->getDirtyAttributes($actualPivotAttributes, $cachedPivotAttributes);

            if (count($dirty) > 0) {
                $id = $aggregate->getEntityKeyValue();

                $this->entityMap->$relation($this->getEntityObject())->updateExistingPivot($id, $dirty);
            }
        }
    }
389344
protected function attachUsingCustomClass($id, array $attributes)
    {
        $records = $this->formatAttachRecords(
            $this->parseIds($id), $attributes
        );

        foreach ($records as $record) {
            $this->newPivot($record, false)->save();
        }
    }
693153
protected function getCachedRelationship(string $relation, $result, Relationship $relationship)
    {
        $pivotColumns = $relationship->getPivotAttributes();

        if (!array_key_exists($relation, $this->pivotAttributes)) {
            $this->pivotAttributes[$relation] = $pivotColumns;
        }

        $wrapper = $this->factory->make($result);

        $hash = $wrapper->getEntityHash();

        if (count($pivotColumns) > 0) {
            $pivotAttributes = [];
            foreach ($pivotColumns as $column) {
                $pivot = $wrapper->getEntityAttribute('pivot');

                $pivotWrapper = $this->factory->make($pivot);

                $pivotAttributes[$column] = $pivotWrapper->getEntityAttribute($column);
            }

            $cachedRelationship = new CachedRelationship($hash, $pivotAttributes);
        } else {
            $cachedRelationship = new CachedRelationship($hash);
        }

        return $cachedRelationship;
    }
248601
protected function hasRelation($eloquent, $id)
    {
        return (method_exists($eloquent, $id) && ($relation = $eloquent->$id())) ? $relation : null;
    }
80713
public function getCascadeDeletesRelationQuery($relation)
    {
        $query = $this->$relation();

        // If this is a force delete and the related model is using soft deletes,
        // we need to use the withTrashed() scope on the relationship query to
        // ensure all related records, plus soft deleted, are force deleted.
        if ($this->isCascadeDeletesForceDeleting()) {
            // Laravel 4.1 has the withTrashed method directly on the Eloquent
            // query builder, however Laravel 4.2+ uses a withTrashed macro
            // on the Eloquent query builder.
            if (!class_exists(SoftDeletingScope::class) || !is_null($query->getMacro('withTrashed'))) {
                $query = $query->withTrashed();
            }
        }

        return $query;
    }
67892
public function sync($ids, $detaching = true)
    {
        $changes = [
            'attached' => [],
            'detached' => [],
            'updated'  => [],
        ];

        $pk = $this->parent->getPk();

        $current = $this->pivot
            ->where($this->localKey, $this->parent->$pk)
            ->column($this->foreignKey);

        $records = [];

        foreach ($ids as $key => $value) {
            if (!is_array($value)) {
                $records[$value] = [];
            } else {
                $records[$key] = $value;
            }
        }

        $detach = array_diff($current, array_keys($records));

        if ($detaching && count($detach) > 0) {
            $this->detach($detach);
            $changes['detached'] = $detach;
        }

        foreach ($records as $id => $attributes) {
            if (!in_array($id, $current)) {
                $this->attach($id, $attributes);
                $changes['attached'][] = $id;
            } elseif (count($attributes) > 0 && $this->attach($id, $attributes)) {
                $changes['updated'][] = $id;
            }
        }

        return $changes;
    }
778806
private function processBeginCache($id,$attributes,$offset)
	{
		$attrs=$this->processAttributes($attributes);
		if(empty($attrs))
			return $this->generatePhpCode("if(\$this->beginCache('$id')):",$offset);
		else
			return $this->generatePhpCode("if(\$this->beginCache('$id', array($attrs))):",$offset);
	}
165218
public function detach(Model $model, $relation, $ids = array(), $touch = true)
    {
        return $model->{$relation}()->detach($ids, $touch);
    }
1154816
public function attach($id, array $attributes = [], $touch = true)
    {
        // Here we will insert the attachment records into the pivot table. Once we have
        // inserted the records, we will touch the relationships if necessary and the
        // function will return. We can parse the IDs before inserting the records.
        foreach ($this->formatAttachRecords((array) $this->parseIds($id), $attributes) as $attribut) {
            $this->newPivot($attribut)->save();
        }

        if ($touch) {
            $this->touchIfTouching();
        }
    }
355714
protected function deleteModels($attribute)
    {
        $data = $this->relationalData[$attribute];

        /** @var ActiveRecord $model */
        foreach ($data['oldModels'] as $model) {
            if ($this->isDeletedModel($model, $attribute)) {
                if (!$model->delete()) {
                    Yii::$app->getDb()->getTransaction()->rollBack();
                    throw new RelationException('Model ' . $model::className() . ' not deleted due to unknown error');
                }
            }
        }

        $this->relationsMap($data['oldRows'], function($row) use ($attribute, $data) {
            if ($this->isDeletedRow($row, $attribute)) {
                Yii::$app->db->createCommand()
                    ->delete($data['junctionTable'], $row)
                    ->execute();
            }
        });
    }