Sync /  attach all related fields to pivot tables

@param $post post object
337097
public function syncRelated($post)
        {

            if ($this->has("categories"))
                $post->categories()->sync(request()->input("categories"));

            if ($this->has("tags"))
                $post->tags()->sync(request()->input("tags"));

        }
1033270
public function saveAssociations(EntityInterface $entity, array $post_data): void
    {
        $table = $this->loadModel();
        Assert::isInstanceOf($table, Table::class);

        $tableAssociations = $table->associations();
        if (empty($tableAssociations)) {
            return;
        }

        foreach ($tableAssociations as $association) {
            if ('manyToMany' !== $association->type()) {
                continue;
            }

            if (!array_key_exists($association->getName(), $post_data)) {
                continue;
            }

            $associationData = [];
            if (is_array($post_data[$association->getName()]) && array_key_exists('_ids', $post_data[$association->getName()]) && !empty($post_data[$association->getName()]['_ids'])) {
                foreach ($post_data[$association->getName()]['_ids'] as $id) {
                    $associationData[] = TableRegistry::getTableLocator()->get($association->className())->get($id);
                }
            }

            Assert::isInstanceOf($association, BelongsToMany::class);
            $association->replaceLinks($entity, $associationData);
        }
    }
169014
protected function autoRelationInsert()
    {
        foreach ($this->relationWrite as $name => $val) {
            $method = Db::parseName($name, 1, false);
            $this->$method()->save($val);
        }
    }
154966
public function savePost(DataObject $post, $data) {
		if ($post->checkPerm('Write') && isset($data['Content'])) {
			$post->Content = $data['Content'];
			if ($this->securityContext->getMember()->Balance >= MicroBlogMember::BALANCE_THRESHOLD) {
				$post->analyseContent();
				$post->write();
			} else {
				$this->queuedJobService->queueJob(new ProcessPostJob($post));
			}
			$html = $post->renderWith('PostContent');
			return $post;
		}
	}
1369943
public function serializeTags(Post $post)
    {
        $event = new GenericDataEvent([
            'class' => 'Icap\BlogBundle\Entity\Post',
            'ids' => [$post->getUuid()],
        ]);
        $this->eventDispatcher->dispatch('claroline_retrieve_used_tags_by_class_and_ids', $event);

        return implode(', ', $event->getResponse());
    }
437512
public function setupPost($post)
    {

        $user    = new User($this->db);
        $comment = new Comment($this->db);
        $vote    = new Vote($this->db);

        $post->img      = $user->getGravatar($post->user);
        $post->comments = $comment->getComments("parentId = ?", [$post->id]);
        $post->vote     = $vote->getVote("parentId = ? AND parentType = ?", [$post->id, "post"]);
        $post->markdown = $this->getMD($post->text);

        return $post;
    }
1083607
public function updatePostViewCount($post)
    {
        $post->increaseViewCounter();
        $this->om->persist($post);
        $this->om->flush();
    }
740612
protected function retrieveConfigPostMetas($post, $postTypeModel)
	{
		$metaKeys = [];
		$metaTaxonomies = [];

		$allKeys = $this->getValidationsKeys($postTypeModel);
		foreach($allKeys as $key => $value){

			$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);

			if(isset($customFieldObject['type']) && $customFieldObject['type'] == 'taxonomy'){

				// We need to get the values from the taxonomy table
				if(array_key_exists('post_type', $customFieldObject)){

					$customfieldPostTypes = $this->getPostTypeIdentifiers($customFieldObject['post_type']);

					// Lets query the post to retrieve all the connected ids
					$taxonomyIds = $post->taxonomies()->whereIn('post_type', $customfieldPostTypes)
						->get();

					// Lets foreach all the posts because we only need the id
					$ids = [];
					foreach($taxonomyIds as $value){
						array_push($ids, $value->id);
					}

					$ids = json_encode($ids);

					$metaTaxonomies[$key] = [
						'meta_key' => $key,
						'meta_value' => $ids,
					];

				}

			// The other items are default
			} else {

				// Register it to the main array so we can query it later
				array_push($metaKeys, $key);

			}

		}

		// Lets query the database to get only the values where we have registered the meta keys
		$postmetaSimple = $post->postmeta()
			->whereIn('meta_key', $metaKeys)
			->select(['meta_key', 'meta_value'])
			->get()
			->keyBy('meta_key')
			->toArray();

		// Lets attach the default post columns
		$defaultPostData = [];

		$defaultPostData['post_title'] = [
			'meta_key' => 'post_title',
			'meta_value' => $post->post_title,
		];

		$defaultPostData['post_name'] = [
			'meta_key' => 'post_name',
			'meta_value' => $post->post_name,
		];

		// Lets merge all the types of configs
		$postmeta = array_merge($postmetaSimple, $metaTaxonomies, $defaultPostData);

		// Return the post meta's
		return $postmeta;
	}
722855
public function updatePivot($entity)
    {
        $keyName = $this->relatedMap->getKeyName();

        $this->updateExistingPivot(
            $entity->getEntityAttribute($keyName),
            $entity->getEntityAttribute('pivot')->getEntityAttributes()
        );
    }
157331
public function setFields($fields)
    {
        foreach ($fields as $name => $value) {
            $this->parameters->addPost($name, $value);
        }
    }
1333662
public function save_meta( $post_id, $post ) {

		$this->post = $post;
		$data       = $this->get_data();

		if ( ! $this->is_active() || empty( $data ) ) {
			return;
		}

		// save compiled data
		update_post_meta( $post_id, $this->slug, $data );
		$data = call_user_func_array( 'array_merge', $data );

		foreach ( $data as $meta_key => $meta_value ) {

			$this->save_meta_data( $meta_key, $meta_value );
		}

	}
1168828
public function savePostMetaToDatabase($postmeta, $postTypeModel, $post, $request = [], $customFieldKey = '')
	{
		// Presetting a empty array so we can append pivot values to the sync function.
		$pivotValue = [];
		$object = [];

		$postmeta = $this->removeUnrequiredMetas($postmeta, $postTypeModel);

		if(!empty($customFieldKey)){
			if($request->hasFile('file')){
				$postmeta[$customFieldKey] = '';
			}
		}

		// Saving the meta values to the database.
		foreach($postmeta as $key => $value){

			$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);
			if($customFieldObject){
				if(array_key_exists('saveable', $customFieldObject)){
					if($customFieldObject['saveable'] === false){
						continue;
					}
				}
			}

			// Lets validate if there is a mutator for this value.
			$value = $this->saveMutator($postTypeModel, $key, $value, $post, $postmeta, $request);

			// If the custom field does not exist, we may not save it.
			$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);
			if(!is_array($customFieldObject)){
				continue;
			}

			$type = 'simple';
			if(array_key_exists('type', $customFieldObject)){
				$type = $customFieldObject['type'];
			}
			switch($type){
				case 'taxonomy':

					if(!array_key_exists('post_type', $customFieldObject) && empty($customFieldObject['post_type'])){
						continue;
					}

					$customfieldPostTypes = $this->getPostTypeIdentifiers($customFieldObject['post_type']);

					if(!is_array($customfieldPostTypes)){
						continue;
					}

					if(!is_array($value)){
						$value = json_decode($value, true);
					}

					// Yes, double.
					if(!is_array($value)){
						continue;
					}

					foreach($value as $valueKey => $valueItem){

						$where = [];

						if($postTypeModel->userCanOnlySeeHisOwnPosts){
							$where[] = ['post_author', '=', Auth::user()->id];
						}

						$where[] = ['id', '=', $valueItem];

						// For each post id give, we need to query the database and validate if this
						// taxonomie of the connect post does exist and we got permission to it.
						$taxonomyPost = NikuPosts::where($where)
							->whereIn('post_type', $customfieldPostTypes)
							->first();

						// If there is a taxonomy result, we can safely add it to the pivot.
						if($taxonomyPost) {
							$pivotValue[$valueItem] = ['taxonomy' => $key];
						}

					}

					$post->taxonomies()->sync($pivotValue);

				break;
				default:

					$object[$key] = $value;

				break;
			}

		}

		$post->saveMetas($object);

		return $post;
	}
723619
public function attach(Threaded $object, $data = null)
    {
        $this->data[] = $object;
        $this->info[] = $data;
    }
111346
public function attach()
    {
        $this->loadModel('Field.FieldInstances');

        if ($this->request->data()) {
            $handler = $this->request->data('handler');
            $info = fieldsInfo($handler);
            $type = !empty($info['type']) ? $info['type'] : null;
            $data = $this->request->data();
            $data['eav_attribute'] = array_merge([
                'table_alias' => $this->_tableAlias,
                'bundle' => $this->_getBundle(),
                'type' => $type,
            ], (array)$this->request->data('eav_attribute'));

            $fieldInstance = $this->FieldInstances->newEntity($data, ['associated' => ['EavAttribute']]);
            $this->_validateSlug($fieldInstance);
            $instanceErrors = $fieldInstance->errors();
            $attributeErrors = $fieldInstance->get('eav_attribute')->errors();
            $success = empty($instanceErrors) && empty($attributeErrors);

            if ($success) {
                $success = $this->FieldInstances->save($fieldInstance, ['associated' => ['EavAttribute']]);
                if ($success) {
                    $this->Flash->success(__d('field', 'Field attached!'));
                    $this->redirect($this->referer());
                }
            }

            if (!$success) {
                $this->Flash->danger(__d('field', 'Field could not be attached'));
            }
        } else {
            $fieldInstance = $this->FieldInstances->newEntity();
        }

        $fieldsInfoCollection = fieldsInfo();
        $fieldsList = $fieldsInfoCollection->combine('handler', 'name')->toArray(); // for form select
        $fieldsInfo = $fieldsInfoCollection->toArray(); // for help-blocks

        $this->title(__d('field', 'Attach New Field'));
        $this->set('fieldsList', $fieldsList);
        $this->set('fieldsInfo', $fieldsInfo);
        $this->set('fieldInstance', $fieldInstance);
    }
1227986
protected function addPivotRelation(string $relation)
    {
        if (!in_array($relation, $this->pivotRelations)) {
            $this->pivotRelations[] = $relation;
        }
    }
880891
public function mungeData($post, BaseModel $model): \stdClass
    {
        // munge a bit so it works for internal data handling
        if (!isset($post->attributes)) {
            // error here, all posts require an attributes tag
            throw new HTTPException('The API received a malformed request', 400, [
                'dev' => 'Bad or incomplete attributes property submitted to the API',
                'code' => '894168146168168168161'
            ]);
        } else {
            $data = $post->attributes;
        }

        if (isset($post->id)) {
            $data->id = $post->id;
        }

        // pull out relationships and convert to simple FKs
        if (isset($post->relationships)) {
            // go through model relationships and look for foreign keys
            $modelRelations = $model->getRelations();
            foreach ($modelRelations as $relation) {
                switch ($relation->getType()) {
                    case PhalconRelation::HAS_ONE:
                    case PhalconRelation::BELONGS_TO:
                        // pull from singular
                        $name = $relation->getTableName('singular');
                        if (isset($post->relationships->$name)) {
                            $fk = $relation->getFields();
                            if (isset($post->relationships->$name->data->id)) {
                                $data->$fk = $post->relationships->$name->data->id;
                            } else {
                                // A bad or incomplete relationship record was submitted
                                // this isn't always an error, it might be that an empty relationship was submitted
                            }
                        }
                        break;

                    case PhalconRelation::HAS_MANY:
                        //TODO: pull plural?
                        break;
                    default:
                        break;
                }
            }
        }

        return $data;
    }
116239
private function syncInserted(array $inserted)
    {
        if ( ! empty($inserted)) {
            $this->newQuery(true)->insert(
                $this->prepareInsertData($inserted)
            );
        }
    }