Basically I have a table "invoices". Those invoices have a table "invoiceItems" associated to them as one invoice to many invoiceItems.
Now I have a route where users can update invoices. The part I cant figure out is how to handle when they update, add, or delete invoiceItems. The front end would be able to send me a JSON object containing all of the data including the IDs for the invoice and the invoiceItems (except the new ones of course). The goal is to update the existing invoice and associated invoiceItems with the new object sent from the front end. I can use the object to create a new invoice no problem, but updating has proven very complicated for me.
My create statement works and looks like this, I would love something similar for update, but I am starting to understand that might not be possible
db.invoice.create(
req.newInvoice, {
include:[
db.invoiceItem
]
}
)
I have tried using transactions as well as mixin methods like set/add/remove etc. With limited success and anything that comes close has so many nested loops comparing the versions it makes my head spin. Is there an easier way to achieve this that I have over looked?
Here's my pared down models for you to see in case it helps:
invoices
module.exports = (sequelize, Sequelize, DataType) => {
const Invoice = sequelize.define('invoice', {
id: {
type: DataType.UUID,
primaryKey: true,
defaultValue: Sequelize.literal( 'uuid_generate_v4()' )
},
userId: {
type: DataType.UUID,
},
createdAt: {
type: DataType.DATE
},
UpdatedAt: {
type: DataType.DATE
}
},{
underscored: true
});
Invoice.associate = models => {
Invoice.hasMany(models.invoiceItem), {
foreignKey: "invoiceId",
onDelete: 'cascade'
}
Invoice.belongsTo(models.user, {
foreignKey: "userId"
})
};
return Invoice
};
invoiceItems
module.exports = (sequelize, Sequelize, DataType) => {
const InvoiceItem = sequelize.define('invoiceItem', {
id: {
type: DataType.UUID,
primaryKey: true,
defaultValue: Sequelize.literal( 'uuid_generate_v4()' )
},
invoiceId: {
type: DataType.UUID,
},
userId: {
type: DataType.UUID,
createdAt: {
type: DataType.DATE
},
updatedAt: {
type: DataType.DATE
}
},{
underscored: true
});
InvoiceItem.associate = models => {
InvoiceItem.belongsTo(models.invoice, {
foreignKey: "invoiceId"
})
InvoiceItem.belongsTo(models.user), {
foreignKey: "userId"
}};
return InvoiceItem
};
Thanks in advance for any help/ideas!
0 comments:
Post a Comment
Thanks