Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do insert multiple entities and return them in TypeORM

Let's say i have a Vote entity. I want to insert an array with 5 votes simultaneously and return them. I have tried : await Vote.save(votes) but that doesnt work and it doesnt return them either. Any ideas?

like image 931
mrgatos Avatar asked Oct 31 '25 18:10

mrgatos


1 Answers

Firstly you need to prepare entities instances (it's not just an object which you must probably have made in some place):

const votesEntities = Vote.create(votes);

And then you could save these entities:

await Vote.save(votesEntities);

But I would advise to use an insert instead of save (because save forms a separate query to DB for each entity) and return previously prepared entities. How it might look in the end:

async insertVotes(votes) {
  const votesEntities = Vote.create(votes);
  await Vote.insert(votesEntities);
  return votesEntities;
} 
like image 73
Art Olshansky Avatar answered Nov 03 '25 09:11

Art Olshansky