Adding a list of items into a PostgreSQL database using SQL syntax

I need to perform multiple table inserts, where the last table relies on the one before it and includes an additional list of items. I am working with pg in conjunction with node.js and JavaScript.

Table 1:

insert into col1, col2 values (1, 2) return col1 as table1_id 

Table 2:

insert into col1 col2 values (table1_id, val1), (table1_id, val2), ... (table1_id, val_n) 

I have observed examples where this has been done with just a single row in the final table. In my case, however, I will have a list of items from val1 to valn that need to be associated with the ID generated from the initial insert in Table 1 and then added to a pre-existing list. The goal is to create a relationship table containing a range of items tied to a record in Table 1.

If anyone has any insights or advice, it would be greatly appreciated.

Thank you

Answer №1

Consider creating a 'dao' layer within your postgres database. This function can take all necessary parameters and return the data needed for frontend display.

By implementing this postgres function, you can efficiently insert all desired rows into the tables.

Here is an example of how you can handle this:

CREATE OR REPLACE FUNCTION function_what_i_want(val1 integer, val2 integer, my_argument integer[])
RETURNS my_schema_and_table[] AS
$BODY$
DECLARE
result my_schema_and_table[];
BEGIN
insert into table1(col1,col2,col3) VALUES (nextval('seq1'),val1, val2);
insert into table2(c1,c2) 
    select currval('seq1'),m.c2
    from unnest(my_argument) m(c2);
END;

If accessing these tables becomes cumbersome in your project, consider storing the lists as json to simplify the process.

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

Demonstrate how to pass a newline character from Ruby on Rails to JavaScript

I am working with a .js.erb file that is activated by a JavaScript function. Within this js.erb file, I have the following snippet of code: event = <%=raw @event.to_json %> $('#preview-event-body').html(event.body); The value of event.bo ...

Retrieve the base64 encoded data from localStorage and showcase it within a div element

After researching a similar question about checking for the existence of a localStorage variable and setting an else if function, and also looking into how to load a base64 image and display it on a div, I have come up with the following code: HTML: <i ...

Experiencing delays when loading more than 200 input fields on the screen due to

So I've been working on a project that involves having potentially unlimited input fields. However, once I add around 200 items, the performance starts to degrade significantly. You can see a demo of this issue here: (To test: Focus on the last input ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

Calculate a range while meeting a specific condition using JavaScript

I am currently working on a project in node.js involving the leap motion technology. I need to create a counter that increments by +1 inside a span element every time the numberOfFingers property of a user's hand is equal to 5. Can someone provide gui ...

Execute a jQuery function only after a form has been submitted for the first time

In the same webpage, I have three lists in HTML format. Whenever an option is selected from the first list, it triggers the population of the second list based on the selection. Similarly, the third list is populated based on the selection from the second ...

Finding the starting point coordinates of a background image that has been adjusted using CSS

I am attempting to determine the exact positioning of a background image that has been shifted off the viewport by applying specific CSS rules. This may be difficult to explain in words, so I have provided a visual example: Black box: Viewport Red box: ...

Server-based WebRTC video streaming

Is it possible to stream a video from the client side and have other viewers join via a server? How can I achieve this setup? ...

The issue of SQLCMD truncating row width during CSV file export

When running an SQL query with sqlcmd and redirecting the output to a CSV file, I am experiencing an issue where each row is being truncated by 257 characters despite specifying "-w 8192" as an argument. sqlcmd -i jira.sql -o JiraQueryResult.csv -h-1 -w 8 ...

Looking for a unique search object specifically designed for mongodb?

I am currently developing my first application using node.js and angular, and I have encountered a challenge that I am struggling to solve. Let's say I have a User Schema like this: User = { firstname: "Bryan", lastname: "Allan", email: "<a ...

Using Fabric.js to manage image controls situated beneath another overlay image

I'm currently working on a canvas user interface using jquery and the fabric.js library. I managed to add an overlay png image with transparency by implementing the code below: var bgImgSrc = bgImg.attr('src'); canvas.setOverlayImage(bgImgS ...

Navigating websites: Clicking buttons and analyzing content

When looking to navigate a website's directory by utilizing buttons on the page or calling the associated functions directly, what language or environment is most suitable for this task? After experimenting with Python, Java, Selenium, and JavaScript, ...

unique list of values separated by commas resulting from a switch statement

I'm currently working on creating a dataset for an SSRS parameter and I'm running into issues with generating distinct values from a case statement. I also need to create a comma-separated array from the result sets. Below is a small example: Sa ...

Here is a method for retrieving all fields within embedded documents at the same level in MongoDB

Thanks to the magic of embedded documents, we can avoid complicated join operations. Yet, I find myself needing to extract all fields on a single level for creating lists or reports. Is there a straightforward way to achieve this? For example; I wish to ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Django: A guide to filtering by DateTimeField while disregarding differences in seconds and milliseconds

When working with Django, I have a model structured like this: class Foo(models.Model): ... created = models.DateTimeField(default=None) ... My query attempts to fetch unique values based on the 'created' field: q = Foo.objects.values(& ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

Converting a string within the range of 31-40 to an integer using parseInt in

I am currently facing an issue with converting a ranged string to an integer. I have age groups such as 21-30, 31-40, 41-50, and so on, and I need to convert the selected string before sending it to the server. I attempted to use the parseInt method, but i ...