Max
Max

Reputation: 217

Sequelize setter error 'invalid input syntax for integer: "[object Object]"'

I am trying to associate a list of contacts to a customer using the associations setter method, however, it always throws the error 'invalid input syntax for integer: "[object Object]"'.

The relevant query mentioned in the error is: UPDATE "contactperson" SET "refCustomerId"=$1,"updatedAt"=$2 WHERE "id" IN ('[object Object]')

This is how I use the setter:

db.customer.findByPk(customerID, {
            include: [{
                model: db.address,
                as: 'address',
            },{
                model: db.contactoption,
                as: 'contactOptions',
            }, {
                model: db.contactperson,
                as: 'contactPersons',
            }]
        }).then(customer => {
customer.setContactPersons([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]);
});

This is the association:

Customer.hasMany(models.contactperson, {
  foreignKey: 'refCustomerId',
  as: 'contactPersons'
});

Any idea what I'm doing wrong?

Upvotes: 2

Views: 5781

Answers (3)

xxx xxx
xxx xxx

Reputation: 1

Exactly what Anatoly posted. I had method declared on TypeScript like:

declare addPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;

When i changed to:

declare createPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;

Everything works so remember - how you describe name of method its very necesary.

Upvotes: 0

Anatoly
Anatoly

Reputation: 22793

You used set<ModelName>s that just updates a link field of given records. If you need to create contactperson record you need to use createContactPerson instead of setContactPersons (NOTE: you cannot create several records at once).

customer.createContactPerson({
  firstName: 'tester',
  lastName: 'tester',
  description: 'lorem ipsum'
});

compare to:

const contactPerson = db.contactperson.findById(1);
if (contactPerson) {
  customer.addContactPersons([contactPerson.id]);
}

set<ModelName>s - replaces old linked records with the new existing ones add<ModelName>s - adds exisiting records in addition to old ones create<ModelName> - create a new non-existing record in addition to old ones

See hasMany special methods

Upvotes: 2

Max
Max

Reputation: 217

I managed to resolve this issue using the following code:

db.contactperson.bulkCreate([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]).then(newContactPersons => {
    customer.setContactPersons(newContactPersons);
});

It's a more complicated approach than intended, but it get's the job done.

Upvotes: 2

Related Questions