Create a new pivot model instance.

@param  \Fly\Database\ActiveRecord\Model  $parent
@param  array   $attributes
@param  string  $table
@param  bool    $exists
@return \Fly\Database\ActiveRecord\Relations\Pivot
6838
public function newPivot(Model $parent, array $attributes, $table, $exists)
	{
		return new Pivot($parent, $attributes, $table, $exists);
	}
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;
    }
1314262
public function save(Entity $entity, $attributes = array())
    {
        foreach ($attributes as $key => $value) {
            $entity->$key = $value;
        }

        // when new record.
        if ($entity->isNew()) {
            $new = $this->create($entity->toArray());
            $entity->exists = true;
            $entity->setPrimaryValue($new->getPrimaryValue());
        }

        // when update.
        else {
            $attributes = $entity->getAttributes(true);
            if (! $attributes ) return;

            return $this->update($attributes, $entity->getPrimaryValue());
        }
    }
12644
private function sync($id, $attributes)
    {
        // Return if the ID is invalid, or attributes is not an array
        if (!isset($id) || !isset($attributes) || empty($attributes)) {
            return $this;
        }

        // Return if there are no relationships of that type
        if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) {
            return $this;
        }

        // Sync each relationship
        foreach ($this->relationships['belongsToMany'] as $join) {

            // The sync option has to be true, the related attribute an array
            if (isset($join['sync']) && $join['sync'] && isset($attributes[$join['alias']]) && is_array($attributes[$join['alias']])) {

                // Delete old values
                $delete = $this->db()->table($join['pivot'])->where($join['localKey'], $id, '=')->delete();

                // Insert new values
                foreach ($attributes[$join['alias']] as $value) {
                    $this->db()->table($join['pivot'])->insert([$join['localKey'] => $id, $join['foreignKey'] => $value]);
                }
            }
        }

        // Return model instance
        return $this;
    }
1033091
protected function createChildContext(array $parentContext, $attribute/*, string $format = null */)
    {
        if (\func_num_args() >= 3) {
            $format = \func_get_arg(2);
        } else {
            // will be deprecated in version 4
            $format = null;
        }

        $context = parent::createChildContext($parentContext, $attribute, $format);
        // format is already included in the cache_key of the parent.
        $context['cache_key'] = $this->getCacheKey($format, $context);

        return $context;
    }
864026
public function newPivot(array $attributes = [], $exists = false)
    {
        $pivot = new Pivot($this->parent, $this->parentMap, $attributes, $this->table, $exists);

        return $pivot->setPivotKeys($this->foreignKey, $this->otherKey);
    }
142811
public function newFromBuilderRecursive(Model $model, array $attributes = [], Relation $parentRelation = null)
    {
        $instance = $model->newInstance([], $exists = true);

        // fill the instance attributes with checking
        $instance->unguard();
        $instance->fill($attributes);
        $instance->reguard();
        // Load relations recursive
        $this->loadRelationsAttributesRecursive($instance);

        // Load pivot
        $this->loadPivotAttribute($instance, $parentRelation);

        return $instance;
    }
961445
protected function getEloquentModel($entity, $exists=false)
    {
        if (empty($entity)) {
            throw new Exception('Object transfered to EntityManager is empty');
        }

        if (! is_object($entity)) {
            throw new Exception('Object transfered to EntityManager is not an object');
        }

        $eloquentModel = Model::newFromDatamapperObject($entity);

        $eloquentModel->exists = $exists;

        return $eloquentModel;
    }
123102
public function associate($model, $attributes = array())
    {
        /**
         * For associated models we will need to create a unique relationship
         * between the parent and the related model. In Cypher we can use the
         * MERGE clause to make sure that the relationship doesn't happen more than once.
         *
         * An example query would be like:
         *
         * HasOne:
         * -------
         *
         * MATCH (user:`User`), (phone:`Phone`)
         * WHERE id(user) = 10892 AND id(phone) = 98522
         * MERGE (user)-[rel:PHONE]-(phone)
         * RETURN rel;
         *
         * BelongsTo:
         * ---------
         *
         * MATCH (account:`Account`), (user:`User`)
         * WHERE id(account) = 10892 AND id(user) = 98522
         * MERGE (account)<-[rel:ACCOUNT]-(user)
         * RETURN rel;
         */

        // Set the relation on the model
        $this->parent->setRelation($this->relation, $model);

        /**
         * Due to the fact that relationships in Graph are entities themselves
         * we will need to treat them as such and in this case what we're looking for is
         * a relationship with an INCOMING direction towards the parent node, in other words
         * it is a relationship with an edge incoming towards the $parent model and we call it
         * an "Edge" relationship.
         */
        return $this->getEdge($model, $attributes);
    }
346885
public function makeChild(array $attributes=[], Node $parent)
    {
        $child = $this->make($attributes);

        $child[$this->getParentIdName()] = $parent->getId();
        $child[$this->getRootIdName()] = $parent[$this->getRootIdName()];

        $child->setParent($parent);

        return $child;
    }
1190822
protected function createAttachRecords($ids, array $attributes)
    {
        $records = [];

        $timed = in_array($this->createdAt(), $this->pivotColumns);

        // To create the attachment records, we will simply spin through the IDs given
        // and create a new record to insert for each ID. Each ID may actually be a
        // key in the array, with extra attributes to be placed in other columns.
        foreach ($ids as $key => $value) {
            $records[] = $this->attacher($key, $value, $attributes, $timed);
        }

        return $records;
    }
993938
public function updateOrCreateNew(array $attributes, $key, array $options = []) : Model
    {
        $query = $this->newQuery();

        if (is_array($key)) {
            foreach ($key as $column) {
                $query->where($column, $attributes[$column]);
            }
        } else {
            $query->where($key, $attributes[$key]);
        }

        /** @var Model|Model $row */
        $row = $query->first();

        if ($row !== null) {
            $row->updateExisting(array_replace($row->getAttributes(), $attributes));

            return $row;
        }

        return $this->fillSave($attributes, $options);
    }
355871
public static function setResponseDataRelationship(array &$mappings, array &$array, array $parent)
    {
        $data = [JsonApiTransformer::RELATIONSHIPS_KEY => []];

        foreach ($array as $propertyName => $value) {
            if (\is_array($value)) {
                self::addRelationshipData($mappings, $parent, $value, $propertyName, $data);
                if (\array_key_exists(Serializer::MAP_TYPE, $value)) {
                    $newData = [];

                    foreach ($value[Serializer::SCALAR_VALUE] as $d) {
                        self::addRelationshipData($mappings, $parent, $d, $propertyName, $newData);

                        if (!empty($d[Serializer::CLASS_IDENTIFIER_KEY])) {
                            $type = $d[Serializer::CLASS_IDENTIFIER_KEY];

                            if (!in_array($propertyName, RecursiveFormatterHelper::getIdProperties($mappings, $type), true)) {
                                $parentType = $d[Serializer::CLASS_IDENTIFIER_KEY];

                                list($idValues, $idProperties) = RecursiveFormatterHelper::getIdPropertyAndValues(
                                    $mappings,
                                    $d,
                                    $parentType
                                );

                                if (!empty($mappings[$parentType]) && !empty($selfLink = $mappings[$parentType]->getRelationshipSelfUrl($propertyName))) {
                                    $href = \str_replace($idProperties, $idValues, $selfLink);
                                    if ($selfLink != $href) {
                                        $propertyNameKey = DataAttributesHelper::transformToValidMemberName($propertyName);
                                        $propertyNameKey = self::camelCaseToUnderscore($propertyNameKey);

                                        $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyNameKey][JsonApiTransformer::LINKS_KEY][JsonApiTransformer::SELF_LINK][JsonApiTransformer::LINKS_HREF] = $href;
                                    }
                                }
                            }
                        }

                        if (!empty($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName])) {
                            $propertyNameKey = DataAttributesHelper::transformToValidMemberName($propertyName);
                            $propertyNameKey = self::camelCaseToUnderscore($propertyNameKey);

                            if (!empty($d[Serializer::CLASS_IDENTIFIER_KEY])) {
                                $type = $d[Serializer::CLASS_IDENTIFIER_KEY];
                                $parentType = $parent[Serializer::CLASS_IDENTIFIER_KEY];

                                //Removes relationships related to the current resource if filtering include resources has been set.
                                if (!empty($mappings[$parentType]) && !empty($mappings[$parentType]->isFilteringIncludedResources())) {
                                    foreach ($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName] as $position => $includedResource) {
                                        if (count($mappings[$parentType]->getIncludedResources()) > 0 &&
                                            false === in_array($type, $mappings[$parentType]->getIncludedResources(), true)
                                        ) {
                                            unset($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName][$position]);
                                        }
                                    }
                                }

                                $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName] = array_filter($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName]);
                                if (!empty($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName][JsonApiTransformer::DATA_KEY])) {
                                    $data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyNameKey][JsonApiTransformer::DATA_KEY][] = $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName][JsonApiTransformer::DATA_KEY];
                                }
                            }
                        }
                    }
                }
            }
        }

        return (array) \array_filter($data);
    }
921491
protected function replicate(EloquentModel $model, array $attributes=[])
    {
        $next = new static($model, $attributes, $this->_maxDepth);
        $next->setParentIdKey($this->getParentIdKey())
             ->setSegmentKey($this->getSegmentKey())
             ->setPathKey($this->getPathKey());

        return $next;
    }
431120
public static function table_create( $table, $fields, $if_not_exists = false ) {

		/**
		 * @var $wpdb wpdb
		 */
		global $wpdb;

		$sql = 'CREATE TABLE';

		if ( true === $if_not_exists ) {
			$sql .= ' IF NOT EXISTS';
		}

		$sql .= " `{$wpdb->prefix}" . self::$prefix . "{$table}` ({$fields})";

		if ( ! empty( $wpdb->charset ) ) {
			$sql .= " DEFAULT CHARACTER SET {$wpdb->charset}";
		}

		if ( ! empty( $wpdb->collate ) ) {
			$sql .= " COLLATE {$wpdb->collate}";
		}

		return self::query( $sql );
	}
72875
public function createModel(iterable $attributes): self
    {
        $this->insert($this->quoteSingleIdentifier($this->getTableName()));

        $valuesAsParams = [];
        foreach ($this->bindAttributes($this->getModelClass(), $attributes) as $quotedColumn => $parameterName) {
            $valuesAsParams[$quotedColumn] = $parameterName;
        }
        $this->values($valuesAsParams);

        return $this;
    }
428559
private function loadVariationsFromSearchIndex(Product $parentProduct, array $attributes)
    {
        $documentSource = $parentProduct->getDocumentSource();
        $childrenIds    = isset($documentSource['children_ids']) ? $documentSource['children_ids'] : [];
        $variation      = false;

        if (!empty($childrenIds)) {
            $childrenIds = array_map('intval', $childrenIds);

            $productCollection = $this->productCollectionFactory->create();
            $productCollection->addIdFilter($childrenIds);

            $configurableAttributes = $this->getAttributesFromConfigurable($parentProduct);
            $allAttributesArray     = [];

            foreach ($configurableAttributes as $attribute) {
                foreach ($attribute->getOptions() as $option) {
                    $allAttributesArray[$attribute['attribute_code']][] = (int) $option->getValue();
                }
            }

            $resultAttributesToFilter = array_merge($attributes, array_diff_key($allAttributesArray, $attributes));

            $this->addFilterByAttributes($productCollection, $resultAttributesToFilter);

            $variationProduct = $productCollection->getFirstItem();

            if ($variationProduct && $variationProduct->getId()) {
                $variation = $this->productRepository->getById($variationProduct->getId());
            }
        }

        return $variation;
    }