getMediaRelationRepository(); $collection = $repository->findAllByTarget( new FindAllByTargetQuery($targetId, $this->getRelationType()) ); foreach ($collection->filterNewMediaIds($currentMediaIds) as $mediaId) { $repository->save($this->createMediaRelation($targetId, $mediaId)); } foreach ($collection->filterRemovedMediaIds($currentMediaIds) as $mediaId) { $repository->remove($this->createMediaRelation($targetId, $mediaId)); } } abstract protected function getRelationType(): string; private function createMediaRelation(string $targetId, string $mediaId): MediaRelation { return (new MediaRelation($this->getRelationType(), $targetId)) ->withSourceId($mediaId); } private function getMediaRelationRepository(): MediaRelationRepositoryInterface { return $this->getServiceLocator()->get(MediaRelationRepositoryInterface::SERVICE_ID); } }