Delete
This page shows how to delete records: with a filter, by primary key, all the records of an entity, and together with related entities. The SQL shown is the one generated for MySQL.
delete returns the number of affected rows: 0 means that no row matched the filter.
const count = await orm.execute('Categories.delete().filter(p => p.id == id)', { id: 9 }) // 1
Delete with a filter
Deletes the details of an order.
Lambda:
Orders.details.delete().filter(p => p.orderId === id)
SQL Result:
DELETE o FROM `Order Details` AS o WHERE o.OrderID = ?
Delete by primary key
When delete() has no filter, it filters by the primary key, whose value is taken from the data passed. The primary key of the order details is made of orderId and productId:
Lambda:
Orders.details.delete()
SQL Result:
DELETE o FROM `Order Details` AS o WHERE (o.OrderID = ? AND o.ProductID = ?)
Delete all the records
To delete all the records of an entity, use deleteAll instead of delete. This prevents deleting all the records by mistake.
Lambda:
Orders.details.deleteAll()
SQL Result:
DELETE FROM `Order Details`
Delete an entity and its related entities
Deletes an order and its details. The order is filtered by its primary key, and each detail sent by its own primary key. The details are deleted first, and then the order.
Lambda:
Orders.delete().include(p => p.details)
SQL Result:
-- the order
DELETE o FROM Orders AS o WHERE o.OrderID = ?
-- each detail sent
DELETE o1 FROM `Order Details` AS o1 WHERE (o1.OrderID = ? AND o1.ProductID = ?)
Code example
Deletes an order with its details and prints the number of orders deleted.
import { orm } from '@lambdaorm/lib'
import { Orders } from './domain/model' // model generated by `lambdaorm build`
(async () => {
try {
await orm.init('./lambdaORM.yaml')
const order = {
id: 1,
customerId: 'ALFKI',
employeeId: 6,
orderDate: '1997-08-24T22:00:00.000Z',
requiredDate: '1997-09-21T22:00:00.000Z',
shippedDate: '1997-09-01T22:00:00.000Z',
shipViaId: 1,
freight: '29.4600',
name: 'Alfreds Futterkiste',
address: 'Obere Str. 57',
city: 'Berlin',
region: null,
postalCode: '12209',
country: 'Germany',
details: [
{
orderId: 1,
productId: 28,
unitPrice: '45.6000',
quantity: '15.0000',
discount: '0.0000'
},
{
orderId: 1,
productId: 39,
unitPrice: '18.0000',
quantity: '21.0000',
discount: '0.0000'
}
]
}
const query = () => Orders.delete().include(p => p.details)
// returns the number of orders deleted
const count = await orm.execute(query, order)
console.log(count)
} catch (error: any) {
console.error(error.stack)
} finally {
// releases the connections
await orm.end()
}
})()