Guide to linking multiple images to a single Post instance

Is it possible to attach each array of images to their post using the foreign key placePlaceId? For example, in the first object with place_id:3, I want to attach all the images with the foreign key placePlaceId:3.

This is my approach to achieving this goal

async getPlaces() {
    let imagesList: Images[] = [];
    const places = await this.repo.find();
    const imageQuery = await this.imagesRepo
      .createQueryBuilder()
      .select('*')
      .getRawMany();
    places.forEach((place, index: number) => {
      for(let i = 0; i < imageQuery.length; i++){
        place.place_id === imageQuery[i].placePlaceId
        ? imagesList.push(imageQuery[i])
        : 0;
      }
      place.images = imagesList;
      this.repo.save(place);
        console.log(place.place_id, imageQuery);
    });
    console.log(imagesList, 'imagesList');
    return places;
  }

Current Result

    [
{
    "place_id": 3,
    "title": "البيك",
    "description": "الذ مطعم سعودي",
    "signature": "المسحب و البروست",
    "isFavorite": false,
    "approved": false,
    "phone": null,
    "website": null,
    "instagram": null,
    "Sunday": "4-11",
    "Monday": "4-11",
    "Tuesday": "4-11",
    "Wednesday": "4-11",
    "Thursday": "4-11",
    "Friday": "4-11",
    "Saturday": "4-11",
    "images": [
        {
            "image_id": 4,
            "image": "http://eatnstays.com/Arabic/wp-content/uploads/2021/06/20180216_134034-12.jpg",
            "image_owner": "google",
            "placePlaceId": 3
        },
        {
            "image_id": 5,
            "image": "http://eatnstays.com/Arabic/wp-content/uploads/2021/06/20180216_134034-12.jpg",
            "image_owner": "google",
            "placePlaceId": 3
        },
        {
            "image_id": 6,
            "image": "https://i.ytimg.com/vi/Fak54PuiW9g/maxresdefault.jpg",
            "image_owner": "google",
            "placePlaceId": 5
        },
        {
            "image_id": 7,
            "image": "https://i.ytimg.com/vi/Fak54PuiW9g/maxresdefault.jpg",
            "image_owner": "google",
            "placePlaceId": 5
        },
         ]
       ]

Expected Result

[
    {
        "place_id": 3,
        "title": "البيك",
        "description": "الذ مطعم سعودي",
        "signature": "المسحب و البروست",
        "isFavorite": false,
        "approved": false,
        "phone": null,
        "website": null,
        "instagram": null,
        "Sunday": "4-11",
        "Monday": "4-11",
        "Tuesday": "4-11",
        "Wednesday": "4-11",
        "Thursday": "4-11",
        "Friday": "4-11",
        "Saturday": "4-11",
        "images": [
            {
                "image_id": 4,
                "image": "http://eatnstays.com/Arabic/wp-content/uploads/2021/06/20180216_134034-12.jpg",
                "image_owner": "google",
                "placePlaceId": 3
            },
            {
                "image_id": 5,
                "image": "http://eatnstays.com/Arabic/wp-content/uploads/2021/06/20180216_134034-12.jpg",
                "image_owner": "google",
                "placePlaceId": 3
            },
             ],
              {
        "place_id": 5,
        "title": "اثراء",
        "description": "مركز الملك عبدالعزيز العالمي",
        "signature": "شامل",
        "isFavorite": false,
        "approved": false,
        "phone": null,
        "website": null,
        "instagram": null,
        "Sunday": "4-11",
        "Monday": "4-11",
        "Tuesday": "4-11",
        "Wednesday": "4-11",
        "Thursday": "4-11",
        "Friday": "4-11",
        "Saturday": "4-11",
        "images": [
            {
                "image_id": 6,
                "image": "https://i.ytimg.com/vi/Fak54PuiW9g/maxresdefault.jpg",
                "image_owner": "google",
                "placePlaceId": 5
            },
            {
                "image_id": 7,
                "image": "https://i.ytimg.com/vi/Fak54PuiW9g/maxresdefault.jpg",
                "image_owner": "google",
                "placePlaceId": 5
            },
             ]
           ]

Answer №1

At first glance, it appears that your current implementation fetches all places and images each time, which could lead to performance issues if the data set grows significantly. It's advisable to avoid this approach in order to prevent potential problems.

The main issue in your code lies in the fact that you are reusing the same imagesList object for all places instead of creating a new instance for each iteration. To address this, you can modify your code to create a new imagesList within the places.forEach loop:

 places.forEach((place, index: number) => {
  let imagesList: Images[] = [];
  for(let i = 0; i < imageQuery.length; i++){
    place.place_id === imageQuery[i].placePlaceId
    ? imagesList.push(imageQuery[i])
    : 0;
  }
  place.images = imagesList;
  this.repo.save(place);
    console.log(place.place_id, imageQuery);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the distinction between using tsserver and eslint for linting code?

As I work on setting up my Neovim's Native LSP environment, a question has arisen regarding JS/TS linter. Could someone explain the distinction between tsserver and eslint as linters? I understand that tsserver is a language server offering features ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

What is the secret behind the checkbox retaining its checked status upon page reload?

My dataTable is loading all data from the MySQL database and the first checkboxes are automatically incremented when a new row is added. However, users may check or uncheck these checkboxes. My goal is to retain the checkbox results even when the page is r ...

Angularjs directive: independent scope and encapsulated elements

Why aren't the contained/child elements rendering when using an isolated scope? I suspect that the parent is not rendered yet. I tried adding a $timeout, but still no luck. If I remove the isolated scope by commenting out scope: {}, it works. How c ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

The Bootstrap modal simply fades away without ever making an appearance

My bootstrap modal is not displaying on desktop, only showing a faded screen. It works fine on mobile and tablet devices. Any ideas why this might be happening? Here is the code: <button type="button" class="btn btn-primary" data-to ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

Fetching a Django view using an AJAX call and extracting the task_id from a Celery task

I have been facing a challenge trying to display data from a celery task in a separate window. My expertise in JavaScript and AJAX is limited, which is where I am encountering issues. Once a view is executed, the celery task commences and the subsequent HT ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Dealing with 404 errors: The role of Nuxt.js and the srcDir option in handling URL

By incorporating the srcDir option into my nuxt.config.js file, I made the decision to transfer the pages, components, and layouts folders to the src directory. Below is how my configuration looks: module.exports = { srcDir: 'src', head: { ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

Tips for adjusting the current window location in Selenium without having to close the window

I am currently working with seleniumIDE My goal is to have a Test Case navigate to a different location depending on a condition (please note that I am using JavaScript for this purpose, and cannot use the if-then plugin at the moment). I have tried using ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Integrate SVG directly into the three.js module to eliminate the need for an additional HTTP request

Currently, I am developing a small website that features a simple 3D animation. The model is extruded from an SVG file loaded using SVGLoader. My goal is to enhance the loading speed by including the SVG as text in my threejs code, eliminating the need for ...

Is it possible to create a VueJS 3 application in a unified ES Module bundle format?

In my Vue3 project, I have configured it with typescript and a main.ts entry file that has a single default export. import { App, createApp } from "vue"; import { createIntl } from "vue-intl"; import Application from "./App.vue&qu ...

Leveraging fullcalendar.io alongside JSONP

I'm currently in the process of integrating public holidays into my FullCalendar application. You can check out FullCalendar here. var actionUrl = @Html.Raw(Json.Encode(@Url.Action("Calendar", "Lecture"))); $('#fullcalendar').ful ...

Is it possible to apply the DRY Concept to this React JS code?

https://i.stack.imgur.com/jcEoA.png import React from "react"; import { Chip, Box } from '@mui/material'; const Browse = () => { const [chip, setChip] = React.useState("all" ...