node.js vue,node mysql sequlize_玩轉Node.js-Sequelize基礎

 2023-11-30 阅读 29 评论 0

摘要:每個索引對象可以設置的值:node.js vue,name:索引名稱,默認模型名稱+字段fields: Array,索引字段vue+MySQL?unique:唯一索引,默認false增加索引的好處就是讓數據庫查詢數據的時候變得更快。mysql2?模型實例對象模型實例對象的概念很

每個索引對象可以設置的值:

node.js vue,name:索引名稱,默認模型名稱+字段

fields: Array,索引字段

vue+MySQL?unique:唯一索引,默認false

增加索引的好處就是讓數據庫查詢數據的時候變得更快。

mysql2?模型實例對象

模型實例對象的概念很好理解,模型對象的作用是操作某張數據表,模型實例對象的作用是操作這張數據表中的數據。

一個模型類對應一個表,一個模型實例對象就是一條對應的表記錄,通過操作這個對象來關聯操作對應的表中的數據,操作模型類就是操作表,操作模型類對象就是操作該表中的某條記錄。

模型類——表

模型實例——記錄

注意在數據庫中,我們通常會把記錄稱為數據,也會把數據稱為記錄,概念是一樣的。

創建模型實例對象

public static build(options: Object): Model | Model[]

options:一個對象,對應的就是表中的字段(模型中定義的屬性),需要注意的是對該對象的操作不會立即反應到實際的數據庫中,需要通過后續的操作進行同步

/**

* 模型類 -> 表

* 模型創建出來的對象 -> 表中某條記錄

*/

// let Kimoo = new UserModel(); //創建了一個User的記錄

let Kimoo = UserModel.build({ //和上面的new是一樣的

// 字段對應的值

username: 'Kimoo',

age: 30,

gender: '男'

});

// 通過new或者build出來的對象不會立即同步到數據庫中,需要使用后續的一些方法來同步

await Kimoo.save();

模型實例對象CRUD操作

模型實例對象.get(key: String):獲取某個屬性(字段)的值。

模型對象.set(key: String, value: any):設置某個屬性(字段)的值。

模型對象.save():驗證該實例,如果通過驗證,則持久化到數據庫中。

模型對象.update(updates: Object):updates:要更新的字段,調用該方法等同于調用.set()然后.save()。

模型對象.destroy():銷毀該實例(假刪除或真刪除)。

// 創建數據模型實例對象 c4az6

// let c4az6 = UserModel.build({

// username: 'c4az6',

// age: 20,

// gender: '男'

// })

// 獲取屬性

/* console.log(`

username: ${c4az6.get('username')}

age: ${c4az6.get('age')}

gender: ${c4az6.get('gender')}

`); */

// 設置屬性

// let res = c4az6.set('age', 21);

// console.log(res.dataValues);

// 通過save方法同步數據到數據庫中

// await c4az6.save();

// 更新字段數據

let res = await UserModel.findById(17);

console.log(res.dataValues);

res.update({username: 'Alex'});

let res2 = await UserModel.findById(18);

res2.update({username: 'Elon', age: 40});

console.log(res2.dataValues);

// 銷毀記錄

res2.destroy();

除了通過模型創建出來的實例對單條數據進行操作,也可以通過模型類對整個對應的表進行操作。

模型.findById(id: Number | String | Buffer):根據主鍵搜索單條記錄,注意是根據主鍵。

findById這個API在6.x的版本中已經被替換為findByPk了

模型.findOne(options: Object):根據條件搜索一條記錄 options.where:搜索條件 Op操作。

模型.findOrCreate(options: Object):搜索特定記錄或創建它(如果沒有對應記錄)options.where:搜索條件。

模型.findAll(findOptions: Object):在數據庫中搜索多個記錄,返回所有數據。

findOptions.where:搜索條件

findOptions.limit:記錄條數限制

findOptions.offset:記錄偏移

findOptions.order:記錄排序方式

模型.findAndCountAll(findOptions: Object):與findAll類似,但是返回值包含 count 屬性,返回數據與總計數。

// 數據模型實例對象查詢相關操作

// findById

// let user = await UserModel.findById(17);

// console.log(user.dataValues);

// findOne 返回一個對象

// let res = await UserModel.findOne({

// where: {

// id: 17

// }

// })

// console.log(res.dataValues);

// 搜索或創建特定記錄,如果不存在則創建,返回數組

// let res = await UserModel.findOrCreate({

// where: {

// id: 30,

// username: 'test'

// }

// })

// console.log(res[0].dataValues);

// 搜索多個記錄,返回數據和總記錄數, 返回數組

// 搜索年齡大于30的所有記錄,這種對象嵌套對象的寫法真惡心,一旦條件變多代碼可讀性會非常差

// let res = await UserModel.findAll({

// where: {

// age: {

// [Op.gt]: 30

// }

// }

// })

// console.log(res.length);

// res.map(item=>{console.log(item.dataValues)});

// 與findAll一樣,但是在返回所有數據的基礎上添加了count統計總記錄數的字段, 返回數組

let res = await UserModel.findAndCountAll()

console.log(res.count)

res.rows.map(item=>{console.log(item.dataValues)});

過濾查詢(Sequelize.Op)

// 過濾查詢

// let res = await UserModel.findAll({

// where: {

// // 單條件過濾

// // username: 'Alex',

// // 多條件 要么年齡大于30,要么性別為女

// [Sequelize.Op.or]: [

// {

// age: {

// [Sequelize.Op.gt]: 30

// }

// },

// {

// gender: '女'

// }

// ]

// }

// })

// res.map(item=>{console.log(item.dataValues)});

// limit 限制記錄查詢

// let res = await UserModel.findAll({

// limit: 5

// });

// for(let i=0; i

// console.log(res[i].dataValues);

// }

// 分頁查詢 limit配合offset一起使用

// let res = await UserModel.findAll({

// limit: 5,

// offset: 5

// });

// console.log(res);

// res.some(item=>console.log(item.dataValues))

// 排序查詢

// 年齡按照降序規則來排序

// let res = await UserModel.findAll({

// order: [['age', 'desc']]

// });

// res.forEach(item=>{console.log(item.dataValues)});

// 返回總記錄數

// let res = await UserModel.count();

// console.log(res);

// 返回2條記錄數和總記錄數

// let res = await UserModel.findAndCountAll({

// limit: 2

// });

// console.log(res.count);

// res.rows.forEach(item=>{console.log(item.dataValues)});

// 計算gender字段為男的年齡總和

// let res = await UserModel.sum('age', {

// where: {

// gender: '男'

// }

// });

// console.log(res);

關聯查詢

1.首先給關聯的字段定義外鍵關系

references: {

model: 關聯的外鍵表,如User

key: 關聯的外鍵表的字段,如id

}

在調用hasOne或hasMany等方法的時候,通過第二個參數設置對象:{foreignKey: 當前關聯表的字段,如uid}

在查詢中使用 include 去設置關聯的外鍵表模型,如:include: [MessageModel]

// 關聯查詢

// 注意:創建模型的前提是你已經有建好了這張表

const MessageModel = sequelize.define('message', {

id: {

type: Sequelize.INTEGER(10),

primaryKey: true,

allowNull: true,

autoIncrement: true

},

uid: { // 關聯其他表的字段,把當前字段定義為外鍵

type: Sequelize.INTEGER(10),

defaultValue: 0,

references: {

model: UserModel,

key: 'id'

}

},

content: {

type: Sequelize.STRING(255),

allowNull: true,

defaultValue: ''

}

}, {

timestamps: false,

freezeTableName: true, // 凍結表名稱

tableName: 'message'

})

// Object.assign(data, {

// id: message.get('id'),

// uid: message.get('uid'),

// username: user.get('username'),

// age: user.get('age'),

// gender: user.get('gender'),

// content: message.get('content')

// });

// console.log(data);

// MessageModel屬于UserModel模型對象

// MessageModel.belongsTo(UserModel, {

// // 關聯外鍵

// foreignKey: 'uid'

// });

// let data2 = await MessageModel.findById(1, {

// // 設置查詢出來的數據包含UserModel數據

// include: [UserModel]

// });

// // console.log(data2);

// console.log(`

// 留言id:${data2.get('id')}

// 留言人名稱:${data2.User.username}

// 留言內容:${data2.get('content')}

// `);

// 關聯查詢與預加載

// 首先給關聯的字段定義外鍵關系

// UserModel包含MessageModel對象,hasMany表示包含多個

UserModel.hasMany(MessageModel, {

foreignKey: 'uid'

});

// 在查詢中使用include去設置關聯的外鍵表模型,如:include:[MessageModel]

let data3 = await UserModel.findById(5, {

include: [MessageModel]

});

data3.messages.map(item => console.log(item.dataValues));

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/186694.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息