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