This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021
UPDATE query
Update takes a WHERE clause argument, just like the read query above.
// Change the name to "Li Hua"
await User.update({ name: "Li hua" }, {
where: {
nameBruce Lee}});Copy the code
The DELETE query
Delete takes a WHERE clause argument, just like the read query above.
// Delete all people named "Jane"
await User.destroy({
where: {
name: "Li hua"}});Copy the code
To destroy all content, use TRUNCATE
// truncate the table
await User.destroy({
truncate: true
});
Copy the code
Create a batch
The Model. BulkCreate method creates multiple records in a query.
Using array objects as data sources,Model. BulkCreate is used similarly
const userList = await Captain.bulkCreate([
{ name: 'Joe' },
{ name: 'bill'}]);console.log(userList.length); / / 2
console.log(userList[0].name); // select * from *;
Copy the code
By default, however,bulkCreate does not run validation on every object to be created (as Create does). To make bulkCreate also run validation, you must set the validate: true parameter. But this degrades performance.
const User = sequelize.define('user', {
bar: {
type: DataTypes.TEXT,
validate: {
len: [4.6]}}});// This will not raise an error and both instances will be created
await FUseroo.bulkCreate([
{ name: 'Joe' },
{ name: 'Too Long Name Test'}]);// This will raise an error and nothing will be created
await User.bulkCreate([
{ name: 'Joe' },
{ name: 'Too Long Name Test'}, {validate: true });
Copy the code
It may be helpful to get the values directly from the user, limiting the columns that are actually inserted. To do this,bulkCreate() takes a fields argument for the array of fields you want to define (the rest of the fields are ignored).
await User.bulkCreate([
{ username: 'Joe' },
{ username: 'bill'.age: 60}, {fields: ['username']});Copy the code
A practical method
count
Method only counts the number of occurrences of elements in the database.
console.log(This has `The ${await Project.count()}A project `);
const amount = await Project.count({
where: {
id: {
[Op.gt]: 25}}});console.log(This has `${amount}Each item id is greater than 25 ');
Copy the code
max
.min
和 sum
A convenient way to
await User.max('age'); / / 40
await User.max('age', { where: { age: { [Op.lt]: 20}}});/ / 10
await User.min('age'); / / 5
await User.min('age', { where: { age: { [Op.gt]: 5}}});/ / 10
await User.sum('age'); / / 55
await User.sum('age', { where: { age: { [Op.gt]: 5}}});/ / 50
Copy the code