在 Sequelize 中,模式(Schema)的使用涉及到定義數(shù)據(jù)表的結(jié)構(gòu),包括字段的類型、約束、索引以及默認(rèn)值等。以下是一些高級(jí)用法的詳細(xì)敘述:
1. 默認(rèn)值 (Default Values)
在 Sequelize 中,你可以為模型字段設(shè)置默認(rèn)值。這對(duì)于當(dāng)記錄被創(chuàng)建而沒有指定某些字段時(shí)非常有用。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { username: { type: Sequelize.STRING, defaultValue: 'NewUser' }, createdAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }});
2. 自定義 Getter 和 Setter
Sequelize 允許你定義自定義的 getter 和 setter 方法,這可以用于格式化數(shù)據(jù)或在數(shù)據(jù)保存到數(shù)據(jù)庫之前對(duì)其進(jìn)行加工。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { firstName: { type: Sequelize.STRING, allowNull: false, get() { const rawValue = this.getDataValue('firstName'); return rawValue ? rawValue.toUpperCase() : null; } }, lastName: { type: Sequelize.STRING, set(value) { this.setDataValue('lastName', value.trim()); } }});
3. 驗(yàn)證
Sequelize 允許你在模型級(jí)別上添加驗(yàn)證。這些驗(yàn)證會(huì)在數(shù)據(jù)保存到數(shù)據(jù)庫之前執(zhí)行。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { email: { type: Sequelize.STRING, allowNull: false, validate: { isEmail: true } }});
4. 虛擬字段 (Virtual Fields)
虛擬字段是不會(huì)保存到數(shù)據(jù)庫中的字段,但可以在模型中定義,并且可以像常規(guī)屬性一樣使用。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { firstName: Sequelize.STRING, lastName: Sequelize.STRING, fullName: { type: Sequelize.VIRTUAL, get() { return `${this.firstName} ${this.lastName}`; } }});
5. 鉤子 (Hooks)
Sequelize 提供了多種鉤子,允許你在數(shù)據(jù)保存、更新或刪除等操作的不同階段運(yùn)行自定義邏輯。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { username: Sequelize.STRING}, { hooks: { beforeCreate: (user, options) => { user.username = user.username.toLowerCase(); } }});
6. 索引
你可以在模型定義中指定索引,這有助于提高數(shù)據(jù)庫查詢的性能。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { username: Sequelize.STRING, email: Sequelize.STRING}, { indexes: [ { unique: true, fields: ['email'] } ]});
這些高級(jí)用法提供了強(qiáng)大的靈活性和控制力,使得 Sequelize 成為一個(gè)功能豐富的 ORM(對(duì)象關(guān)系映射)工具。通過這些用法,你可以更好地定義和操作你的數(shù)據(jù)模型。
2. Schema常用配置說明
在 Sequelize 中,定義模型時(shí)可以為每個(gè)字段(屬性)指定多種配置項(xiàng)。以下是一些常見的屬性及其詳細(xì)說明:
1. type
描述: 指定字段的數(shù)據(jù)類型。
示例:
Sequelize.STRING
,Sequelize.INTEGER
,Sequelize.DATE
等。
2. defaultValue
描述: 為字段指定默認(rèn)值。
示例:
defaultValue: Sequelize.NOW
或defaultValue: 'some default value'
。
3. allowNull
描述: 設(shè)置字段是否可以為
null
。示例:
allowNull: false
表示字段不可為空。
4. unique
描述: 確保字段值在整個(gè)表中是唯一的。
示例:
unique: true
或unique: 'unique_constraint_name'
。
5. primaryKey
描述: 將字段設(shè)置為表的主鍵。
示例:
primaryKey: true
。
6. autoIncrement
描述: 對(duì)于整數(shù)字段,設(shè)置為自動(dòng)遞增。
示例:
autoIncrement: true
通常用于主鍵。
7. validate
描述: 為字段添加驗(yàn)證規(guī)則。
示例:
javascript代碼解讀復(fù)制代碼validate: { isEmail: true, notEmpty: true}
8. get
和 set
描述: 自定義字段的 getter 和 setter 函數(shù)。
示例:
javascript代碼解讀復(fù)制代碼get() { return this.getDataValue('fieldName');},set(value) { this.setDataValue('fieldName', value);}
9. field
描述: 指定數(shù)據(jù)庫中對(duì)應(yīng)的列名稱(如果與模型中的字段名不同)。
示例:
field: 'column_name_in_database'
。
10. references
描述: 用于建立外鍵關(guān)系,指向另一個(gè)模型的字段。
示例:
javascript代碼解讀復(fù)制代碼references: { model: 'OtherModel', key: 'id'}
11. onDelete
和 onUpdate
描述: 定義外鍵的級(jí)聯(lián)行為。
示例:
onDelete: 'CASCADE'
,onUpdate: 'NO ACTION'
。
12. comment
描述: 為字段添加注釋。
示例:
comment: 'This is a comment'
。
13. typeValidation
描述: 啟用數(shù)據(jù)類型級(jí)別的驗(yàn)證。
示例:
typeValidation: true
。
這些屬性提供了豐富的配置選項(xiàng),可以讓你詳細(xì)地定義你的數(shù)據(jù)模型,確保數(shù)據(jù)的完整性和正確性。通過合理運(yùn)用這些屬性,可以創(chuàng)建出既強(qiáng)大又靈活的數(shù)據(jù)庫模式。
3. Sequelize的Schema配合Antd ProTable
要使用 Sequelize 和 Ant Design Pro Table 實(shí)現(xiàn)一個(gè)集成查詢、篩選、排序和分頁功能的前后端數(shù)據(jù)交互,你需要在前端設(shè)置好 Pro Table,并在后端配置 Sequelize 來處理相應(yīng)的請(qǐng)求。以下是大致的步驟:
后端 (使用 Sequelize)
假設(shè)有一個(gè)名為 Item
的 Sequelize 模型,需要?jiǎng)?chuàng)建一個(gè) API 端點(diǎn)來處理前端發(fā)送的請(qǐng)求:
設(shè)置 Express 路由:
javascript代碼解讀復(fù)制代碼app.get('/api/items', async (req, res) => { // 使用 req.query 獲取前端發(fā)送的參數(shù) const { current, pageSize, sorter, filter } = req.query; // 處理分頁 const limit = pageSize ? parseInt(pageSize) : 10; const offset = current ? (current - 1) * limit : 0; // 處理排序 let order = []; if (sorter) { // 假設(shè) sorter 格式為 'field_desc' 或 'field_asc' const [field, orderType] = sorter.split('_'); order.push([field, orderType.toUpperCase()]); } // 處理篩選 // 這里的 filter 處理取決于你的具體邏輯 // 構(gòu)建查詢參數(shù) const options = { where: filter, order: order, offset: offset, limit: limit, }; // 查詢數(shù)據(jù) try { const { count, rows } = await Item.findAndCountAll(options); res.json({ data: rows, total: count, success: true, }); } catch (error) { res.status(500).send({ message: error.message }); }});
前端 (使用 Ant Design Pro Table)
在前端,需要配置 Pro Table 來發(fā)送合適的請(qǐng)求并展示數(shù)據(jù):
配置 Pro Table:
jsx代碼解讀復(fù)制代碼import ProTable from '@ant-design/pro-table';const TableList = () => { const columns = [ // 定義列 { title: 'Name', dataIndex: 'name', sorter: true, filter: true }, // 更多列... ]; return ( <ProTable columns={columns} request={async (params, sorter, filter) => { // 處理 params,sorter,filter 以匹配后端 API const requestParams = { ...params, sorter: Object.keys(sorter).length ? `${Object.keys(sorter)[0]}_${sorter[Object.keys(sorter)[0]]}` : '', filter: filter, }; // 發(fā)送請(qǐng)求到后端 const response = await fetch('/api/items', { method: 'GET', params: requestParams, }); const data = await response.json(); return { data: data.data, success: data.success, total: data.total, }; }} rowKey="id" pagination={{ pageSize: 10, }} search={{ filterType: 'light', }} /> );};export default TableList;
這個(gè)示例展示了如何在前端使用 Pro Table 發(fā)送請(qǐng)求,并在后端使用 Sequelize 處理這些請(qǐng)求。作為開發(fā)者,你可能需要根據(jù)自己的數(shù)據(jù)模型和業(yè)務(wù)需求調(diào)整篩選和排序的邏輯。通過這種方式,可以構(gòu)建一個(gè)強(qiáng)大的、支持查詢、篩選、排序和分頁的數(shù)據(jù)表格。