在 Sequelize 中,模式(Schema)的使用涉及到定義數(shù)據(jù)表的結(jié)構(gòu),包括字段的類型、約束、索引以及默認(rèn)值等。以下是一些高級用法的詳細(xì)敘述:
1. 默認(rèn)值 (Default Values)
在 Sequelize 中,你可以為模型字段設(shè)置默認(rèn)值。這對于當(dāng)記錄被創(chuàng)建而沒有指定某些字段時非常有用。
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ù)庫之前對其進行加工。
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. 驗證
Sequelize 允許你在模型級別上添加驗證。這些驗證會在數(shù)據(jù)保存到數(shù)據(jù)庫之前執(zhí)行。
javascript
代碼解讀
復(fù)制代碼const User = sequelize.define('user', { email: { type: Sequelize.STRING, allowNull: false, validate: { isEmail: true } }});
4. 虛擬字段 (Virtual Fields)
虛擬字段是不會保存到數(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ù)保存、更新或刪除等操作的不同階段運行自定義邏輯。
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'] } ]});
這些高級用法提供了強大的靈活性和控制力,使得 Sequelize 成為一個功能豐富的 ORM(對象關(guān)系映射)工具。通過這些用法,你可以更好地定義和操作你的數(shù)據(jù)模型。
2. Schema常用配置說明
在 Sequelize 中,定義模型時可以為每個字段(屬性)指定多種配置項。以下是一些常見的屬性及其詳細(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
描述: 確保字段值在整個表中是唯一的。
示例:
unique: true
或unique: 'unique_constraint_name'
。
5. primaryKey
描述: 將字段設(shè)置為表的主鍵。
示例:
primaryKey: true
。
6. autoIncrement
描述: 對于整數(shù)字段,設(shè)置為自動遞增。
示例:
autoIncrement: true
通常用于主鍵。
7. validate
描述: 為字段添加驗證規(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ù)庫中對應(yīng)的列名稱(如果與模型中的字段名不同)。
示例:
field: 'column_name_in_database'
。
10. references
描述: 用于建立外鍵關(guān)系,指向另一個模型的字段。
示例:
javascript代碼解讀復(fù)制代碼references: { model: 'OtherModel', key: 'id'}
11. onDelete
和 onUpdate
描述: 定義外鍵的級聯(lián)行為。
示例:
onDelete: 'CASCADE'
,onUpdate: 'NO ACTION'
。
12. comment
描述: 為字段添加注釋。
示例:
comment: 'This is a comment'
。
13. typeValidation
描述: 啟用數(shù)據(jù)類型級別的驗證。
示例:
typeValidation: true
。
這些屬性提供了豐富的配置選項,可以讓你詳細(xì)地定義你的數(shù)據(jù)模型,確保數(shù)據(jù)的完整性和正確性。通過合理運用這些屬性,可以創(chuàng)建出既強大又靈活的數(shù)據(jù)庫模式。
3. Sequelize的Schema配合Antd ProTable
要使用 Sequelize 和 Ant Design Pro Table 實現(xiàn)一個集成查詢、篩選、排序和分頁功能的前后端數(shù)據(jù)交互,你需要在前端設(shè)置好 Pro Table,并在后端配置 Sequelize 來處理相應(yīng)的請求。以下是大致的步驟:
后端 (使用 Sequelize)
假設(shè)有一個名為 Item
的 Sequelize 模型,需要創(chuàng)建一個 API 端點來處理前端發(fā)送的請求:
設(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ā)送合適的請求并展示數(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ā)送請求到后端 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;
這個示例展示了如何在前端使用 Pro Table 發(fā)送請求,并在后端使用 Sequelize 處理這些請求。作為開發(fā)者,你可能需要根據(jù)自己的數(shù)據(jù)模型和業(yè)務(wù)需求調(diào)整篩選和排序的邏輯。通過這種方式,可以構(gòu)建一個強大的、支持查詢、篩選、排序和分頁的數(shù)據(jù)表格。