Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone/copy instance item/row in sequelize

I tried to find a way to copy/clone instances in Sequelize but without success. Is there any way to do it with a built-in function or without? What I want is to simply copy rows in the database and the new item should have only a different id.

like image 998
agims7 Avatar asked Aug 07 '18 11:08

agims7


3 Answers

There is no such direct function for that , What you can do is :

  1. Fetch the object that you want to clone/copy
  2. Remove Primary Key from it
  3. Make a new entry from it

    model.findOne({ //<---------- 1
                    where : { id : 1 } , 
                    raw : true })
    .then(data => {
        delete data.id; //<---------- 2
        model.create(data); //<---------- 3
    })
    
like image 139
Vivek Doshi Avatar answered Nov 14 '22 05:11

Vivek Doshi


As said, there is no such direct function for that (thanks Vivek)

If you find useful, place the following code on your model class:

async clone() {
    let cData = await THISISMYMODEL.findOne({
        where: { id: this.id},
        raw: true,
    });

    delete cData.id;
    return await THISISMYMODEL.create(data);
}

Take into account that "THISISMYMODEL" should be the model class defined and "id" the primary key attribute used.

Also take into account the use of Foreign Keys (relations with other models), it will use the same keys. Otherwise you should clone those instances too.

like image 35
Adrian Sanchez Avatar answered Nov 14 '22 07:11

Adrian Sanchez


You may need to update the name though or some other field to identify it as a copy,

const data = await model.findOne({ where: {id: 1}, raw:  true, attributes: { exclude: ['id'] } });

data.name = data.name + '(copy)';
const newRecord = await model.create(data);
like image 31
adnan shuja Avatar answered Nov 14 '22 05:11

adnan shuja