Sorts $relatedContentItems to match order from $relatedContentIds.

@param array $relatedContentItems
@param array $relatedContentIds
424574
private function sortByIdOrder(array &$relatedContentItems, array $relatedContentIds)
    {
        $sortedIdList = array_flip($relatedContentIds);

        $sorter = function (Content $content1, Content $content2) use ($sortedIdList) {
            if ($content1->id === $content2->id) {
                return 0;
            }

            return ($sortedIdList[$content1->id] < $sortedIdList[$content2->id]) ? -1 : 1;
        };

        usort($relatedContentItems, $sorter);
    }
261733
public function add_related_badges($relatedids) {
        global $DB;
        $relatedbadges = array();
        foreach ($relatedids as $relatedid) {
            $relatedbadge = new stdClass();
            $relatedbadge->badgeid = $this->id;
            $relatedbadge->relatedbadgeid = $relatedid;
            $relatedbadges[] = $relatedbadge;
        }
        $DB->insert_records('badge_related', $relatedbadges);
    }
305449
private function cascadePersist(object $document, array &$visited) : void
    {
        $class = $this->dm->getClassMetadata(get_class($document));

        $associationMappings = array_filter(
            $class->associationMappings,
            static function ($assoc) {
                return $assoc['isCascadePersist'];
            }
        );

        foreach ($associationMappings as $fieldName => $mapping) {
            $relatedDocuments = $class->reflFields[$fieldName]->getValue($document);

            if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
                if ($relatedDocuments instanceof PersistentCollectionInterface) {
                    if ($relatedDocuments->getOwner() !== $document) {
                        $relatedDocuments = $this->fixPersistentCollectionOwnership($relatedDocuments, $document, $class, $mapping['fieldName']);
                    }
                    // Unwrap so that foreach() does not initialize
                    $relatedDocuments = $relatedDocuments->unwrap();
                }

                $count = 0;
                foreach ($relatedDocuments as $relatedKey => $relatedDocument) {
                    if (! empty($mapping['embedded'])) {
                        [, $knownParent ] = $this->getParentAssociation($relatedDocument);
                        if ($knownParent && $knownParent !== $document) {
                            $relatedDocument               = clone $relatedDocument;
                            $relatedDocuments[$relatedKey] = $relatedDocument;
                        }
                        $pathKey = CollectionHelper::isList($mapping['strategy']) ? $count++ : $relatedKey;
                        $this->setParentAssociation($relatedDocument, $mapping, $document, $mapping['fieldName'] . '.' . $pathKey);
                    }
                    $this->doPersist($relatedDocument, $visited);
                }
            } elseif ($relatedDocuments !== null) {
                if (! empty($mapping['embedded'])) {
                    [, $knownParent ] = $this->getParentAssociation($relatedDocuments);
                    if ($knownParent && $knownParent !== $document) {
                        $relatedDocuments = clone $relatedDocuments;
                        $class->setFieldValue($document, $mapping['fieldName'], $relatedDocuments);
                    }
                    $this->setParentAssociation($relatedDocuments, $mapping, $document, $mapping['fieldName']);
                }
                $this->doPersist($relatedDocuments, $visited);
            }
        }
    }
725422
public function manyToMany ($relatedTable, $relationalTable, $relatedKey = null, $key = null, $relationIdentifier = null)
		{
			if (is_null($relationIdentifier)) {
				$relationIdentifier = $relatedTable;
			}

			$this->relations[$relationIdentifier] = new ManyToMany(
				$this,
				$this->schema->getTable($relatedTable, true),
				$this->schema->getTable($relationalTable, true),
				$key,
				$relatedKey
			);

			return $this;
		}
53504
private function cleanRelatedObjects(&$relatedObjects)
    {
        $existEmbObjects = [];
        foreach ($relatedObjects as $key => $existEmbObject) {
            $existEmbObjects[$key] = $existEmbObject;
            unset($relatedObjects[$key]);
        }

        return $existEmbObjects;
    }
853054
public void addRelationshipFilter(RelatedFinder relatedFinder, Operation filter)
    {
        Operation existing = this.filters.get(relatedFinder);
        this.filters.put(relatedFinder, existing == null ? filter : existing.or(filter));
    }
1361423
public function relatedPost(ApiRequest $request, $resourceModel)
    {
        $requestModel = $request->asRequestModel();

        $this->validate($requestModel, $this->getCreatingRules());

        $relation = $this->getRelation($resourceModel);

        return $this->createRelationshipModel($relation, $requestModel);
    }
601028
protected function includeRelated(
        DocumentInterface $document,
        ResourceInterface $resource,
        RequestInterface $request
    ): void {
        foreach ($resource->relationships()->all() as $relationship) {
            $shouldIncludeRelationship = $request->requestsInclude($relationship->name());
            $subRequest = $request->createSubRequest($relationship->name(), $resource);
            foreach ($relationship->related()->all() as $related) {
                if ($shouldIncludeRelationship) {
                    $document->included()->merge($related);
                }
                $this->includeRelated($document, $related, $subRequest);
                $this->cleanUpResource($document->included()->get($related->type(), $related->id()), $subRequest);
            }
        }
    }
151392
private function processRelationQueue(Bag $relationQueue)
    {
        foreach ($relationQueue as $source => $links) {
            $entity = $this->query->getContent($source);
            $relations = [];
            foreach ($links as $linkKey) {
                $relation = $this->query->getContent($linkKey);
                $relatedKey = (string) $relation->getContentType();

                $relations[$relatedKey][] = $relation->getId();
            }
            /** @var Collection\Relations $related */
            $related = $this->em->createCollection(Entity\Relations::class);
            $related->setFromPost(['relation' => $relations], $entity);
            $entity->setRelation($related);
            $this->em->save($entity);
        }
    }
741418
public function delete_related_badge($relatedid) {
        global $DB;
        $sql = "(badgeid = :badgeid AND relatedbadgeid = :relatedid) OR " .
               "(badgeid = :relatedid2 AND relatedbadgeid = :badgeid2)";
        $params = ['badgeid' => $this->id, 'badgeid2' => $this->id, 'relatedid' => $relatedid, 'relatedid2' => $relatedid];
        return $DB->delete_records_select('badge_related', $sql, $params);
    }
874566
protected function sortManyManyRelation(
        ManyManyList $relation,
        array $idList,
        array $rawList,
        DataObjectInterface $record,
        $sortColumn
    ) {
        $relation->getForeignID();
        $ownerIdField = $relation->getForeignKey();
        $fileIdField = $relation->getLocalKey();
        $joinTable = '"' . $relation->getJoinTable() . '"';
        $sort = 0;
        foreach ($rawList as $id) {
            if (in_array($id, $idList)) {
                // Use SQLUpdate to update the data in the join-table.
                // This is safe to do, since new records have already been written to the DB in the
                // parent::saveInto call.
                SQLUpdate::create($joinTable)
                    ->setWhere([
                        "\"$ownerIdField\" = ?" => $record->ID,
                        "\"$fileIdField\" = ?" => $id
                    ])
                    ->assign($sortColumn, $sort++)
                    ->execute();
            }
        }
    }
988948
public function relateContentNodes($contentNodeList, $chapterId) {
        // Reverse node list because the Weighable behavior sorts different from the way
        // the CMS sends us the nodes.
        $contentNodeList = array_reverse($contentNodeList);
        foreach ($contentNodeList as $contentNode) {
            $node = $this->_getValidContentNodeData($contentNode);

            // Save ContentNode
            $node['chapter_id'] = $chapterId;
            $contentNodeId = $this->_insertContentNode($node);

            // @todo Move everything below here to Model_ContentNode::afterInsert()

            // Determine content type
            $contentTypeModelName = 'Model_'.$node['model'];
            $contentTypeModel = new $contentTypeModelName();

            // Check for existing id
            $data = $node['data'];
            if (empty($data['id'])) {
                // If no id is present, create a new subtype record
                $contentTypeId = $contentTypeModel->insert($data);
            } else {
                // Update the chapter subtype's content
                $contentTypeModel->update($data, 'id = '.$contentTypeModel->getAdapter()->quote($data['id']));
                $contentTypeId = $data['id'];
            }

            // Relate the ContentNode to the subtype record
            Garp_Content_Relation_Manager::relate(array(
                'modelA' => 'Model_ContentNode',
                'modelB' => $contentTypeModel,
                'keyA'   => $contentNodeId,
                'keyB'   => $contentTypeId,
            ));
        }
    }
1150561
public function withHasMany(array $data, $relatedModel, $relation_name){
        $this->withHasMany['relation'] = $relation_name;
        foreach($data as $k=>$v){
            $this->withHasMany['data'][] = new $relatedModel($v);
        }
        return $this;
    }
608495
protected function saveHasManyData($relatedModel, HasMany $hasMany, $data, $relationName)
    {
        if ($this->exists) {
            $models = [];
            $pk = $hasMany->getRelated()->primaryKey;
            $fk = $hasMany->getForeignKeyName();

            foreach ((array)$data as $d) {
                /** @var Model $model */
                if (empty($pkValue = array_get($d, $pk))) {
                    $model = $relatedModel::findCompositeForeignKeyModel($this->{$this->primaryKey}, $d);
                } else {
                    $model = $relatedModel::find($pkValue);
                }
                if (!empty($model)) {
                    /** @var Model $parent */
                    $fkId = array_get($d, $fk);
                    if (array_key_exists($fk, $d) && is_null($fkId)) {
                        //Foreign key field is set to null therefore delete the child record.
                        $model->delete();
                        continue;
                    } elseif (!empty($fkId) &&
                        $fkId !== $this->{$this->primaryKey} &&
                        (null !== $parent = static::find($fkId))
                    ) {
                        //Foreign key field is set but the id belongs to a different parent than this parent.
                        //There the child is adopted by the supplied parent id (foreign key).
                        $relatedData = [$relationName => [$d]];
                        $parent->update($relatedData);
                        continue;
                    } else {
                        $model->fill($d);
                    }
                } else {
                    // not found, create a new one
                    $model = new $relatedModel($d);
                }
                $models[] = $model;
            }

            $hasMany->saveMany($models);
        }
    }
858880
private function getArchiveItems($otherNews, $limit, $sort, $related, $params)
    {
        $filter = array(
            'Live' => 1, // only work on live items
        );
        if (class_exists('Translatable')) {
            $filter['Locale'] = Translatable::get_current_locale();
        }
        $exclude = array(
            'PublishFrom:GreaterThan' => SS_Datetime::now()->Rfc2822(), // same as above

        );

        if ($related && $params['Action'] === 'show') { // @todo This only works with the default action, not allowed actions
            $filter = array_merge(
                $filter,
                array('Tags.ID:ExactMatch' => $otherNews->Tags()->column('ID'))
            );
            $exclude = array_merge(
                $exclude, array('ID' => $otherNews->ID)
            );
        }
        if ($sort) {
            $sort = 'RAND()';
        }
        /** @var DataList||News[] $news */
        $news = News::get()
            ->filter($filter)
            ->exclude($exclude)
            ->sort($sort)
            ->limit($limit);

        return $news;
    }
829357
def get_related_galleries(gallery, count=5):
    
    # just get the first cat. If they assigned to more than one, tough
    try:
        cat = gallery.sections.all()[0]
        related = cat.gallery_categories.filter(published=True).exclude(id=gallery.id).order_by('-id')[:count]
    except:
        related = None
    return {'related': related, 'MEDIA_URL': settings.MEDIA_URL}
791148
protected function restoreObjectRelations(IObject $object, array $relatedValues)
    {
        foreach ($relatedValues as $propertyName => $value) {
            $property = $object->getProperty($propertyName);
            $property->setInitialValue(null);
            $property->setValue($value);
        }
    }