<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Sequelize 教程 > 原文: [http://zetcode.com/javascript/sequelize/](http://zetcode.com/javascript/sequelize/) Sequelize 教程展示了如何使用 Sequelize ORM 在 JavaScript 中對數據庫進行編程。 ## Sequelize Sequelize 是 Node.js 的基于 Promise 的 ORM。 它可與 PostgreSQL,MySQL,SQLite 和 MSSQL 方言配合使用,并具有可靠的事務支持,關系,讀取復制等功能。 對象關系映射(ORM)是一種從面向對象的語言訪問關系數據庫的技術。 在本教程中,我們使用 MySQL。 ## 設置續集 我們初始化一個 Node 應用并安裝 Sequelize 和 MySQL 適配器。 ```js $ nodejs -v v10.12.0 ``` 我們使用 Node 版本 10.12.0。 ```js $ npm init ``` 我們啟動一個新的 Node 應用。 ```js $ npm i sequelize $ nmp i mysql2 ``` 我們安裝 Seqelize 和 MySQL 驅動程序。 有兩個驅動程序可用:`mysql`和`mysql2`; 我們選擇了后者。 ## Sequelize 認證 在第一個示例中,我們創建與 MySQL 數據庫的連接。 `authenticate.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/testdb'; const sequelize = new Sequelize(path, { operatorsAliases: false }); sequelize.authenticate().then(() => { console.log('Connection established successfully.'); }).catch(err => { console.error('Unable to connect to the database:', err); }).finally(() => { sequelize.close(); }); ``` 該示例在連接到 MySQL 數據庫時顯示一條消息。 ```js const Sequelize = require('sequelize'); ``` 我們加載 Sequelize 模塊。 ```js const path = 'mysql://user12:12user@localhost:3306/testdb'; ``` 這是 MySQL 連接路徑。 它包含用戶名,密碼,主機名,數據庫端口和數據庫名稱。 ```js const sequelize = new Sequelize(path, { operatorsAliases: false }); ``` 我們實例化 Sequelize。 ```js sequelize.authenticate().then(() => { console.log('Connection established successfully.'); ... ``` `authenticate()`方法通過嘗試向數據庫進行認證來測試連接。 建立連接后,我們將打印一條消息。 ```js }).catch(err => { console.error('Unable to connect to the database:', err); ... ``` 如果發生錯誤,我們將打印一條錯誤消息。 ```js }).finally(() => { sequelize.close(); }); ``` 最后,我們關閉數據庫連接。 ```js $ node authenticate.js Executing (default): SELECT 1+1 AS result Connection established successfully ``` 這是輸出。 輸出也包括調試輸出。 ## Sequelize 模型定義 `Model`代表數據庫中的表。 此類的實例代表數據庫行。 Sequelize 的`define()`方法定義了一個新模型。 `define_model.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false }); let Dummy = sequelize.define('dummy', { description: Sequelize.STRING }); Dummy.sync().then(() => { console.log('New table created'); }).finally(() => { sequelize.close(); }) ``` 該示例創建一個簡單的模型。 它將模型保存到數據庫表中。 ```js let Dummy = sequelize.define('dummy', { description: Sequelize.STRING }); ``` 創建了一個新模型`Dummy`。 第一個參數是型號名稱。 第二個參數由屬性組成,這些屬性是表列。 在我們的例子中,我們有一個列名`description`,它是`String`類型。 ```js Dummy.sync().then(() => { console.log('New table created'); }).finally(() => { sequelize.close(); }) ``` `sync()`方法將模型同步到數據庫。 實際上,它將創建一個新的`dummies`表。 (表名是復數的。) ```js $ node model_define.js Executing (default): CREATE TABLE IF NOT EXISTS `dummies` (`id` INTEGER NOT NULL auto_increment , `description` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; Executing (default): SHOW INDEX FROM `dummies` New table created ``` 這是輸出。 默認情況下,Sequelize 提供日志記錄。 可以使用`logging`選項將其關閉。 ```js mysql> describe dummies; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | description | varchar(255) | YES | | NULL | | | createdAt | datetime | NO | | NULL | | | updatedAt | datetime | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) ``` 我們檢查在 MySQL 中創建的表。 Sequelize 還創建了另外兩個列:`createdAt`和`updatedAt`。 可以使用`timestamps`選項將其關閉。 ## Sequelize 刪除表 用`drop()`方法刪除一個表。 `drop_table.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Dummy = sequelize.define('dummy', { description: Sequelize.STRING }); Dummy.drop().then(() => { console.log('table deleted'); }).finally(() => { sequelize.close(); }); ``` 該示例刪除`dummies`表。 ## Sequelize 時間戳 Sequelize 自動為模型添加時間戳。 我們可以使用`timestamps`控制此行為。 `timestamps.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false, define: { timestamps: false } }); let Dummy = sequelize.define('dummy', { description: Sequelize.STRING }); sequelize.sync({force: true}).then(() => { Dummy.create({ description: 'test 1' }).then(() => { console.log('table created'); }).finally(() => { sequelize.close(); }); }); ``` 該示例創建一個沒有時間戳的表。 ```js const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false, define: { timestamps: false } }); ``` 在這里,我們關閉時間戳記。 ```js mysql> describe dummies; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | description | varchar(255) | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) ``` 我們確認表中沒有時間戳。 ## Sequelize 批量創建 `bulkCreate()`方法創建并批量插入多個實例。 該方法采用對象數組。 `bulk_create_notes.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); let notes = [ { description: 'Tai chi in the morning' }, { description: 'Visited friend' }, { description: 'Went to cinema' }, { description: 'Listened to music' }, { description: 'Watched TV all day' }, { description: 'Walked for a hour' }, ]; sequelize.sync({ force: true }).then(() => { Note.bulkCreate(notes, { validate: true }).then(() => { console.log('notes created'); }).catch((err) => { console.log('failed to create notes'); console.log(err); }).finally(() => { sequelize.close(); }); }); ``` 表格示例記錄了幾行。 ```js const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); ``` 我們禁用日志記錄。 ```js sequelize.sync({ force: true }).then(() => { ``` `sqeuelize.syn()`同步所有型號。 在`force`選項丟棄的表,如果它的創建之前就存在。 ```js Note.bulkCreate(notes, { validate: true }).then(() => { console.log('notes created'); ... ``` `bulkCreate()`創建具有六行的表格。 ```js mysql> select * from notes; +----+------------------------+---------------------+---------------------+ | id | description | createdAt | updatedAt | +----+------------------------+---------------------+---------------------+ | 1 | Tai chi in the morning | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | | 2 | Visited friend | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | | 3 | Went to cinema | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | | 4 | Listened to music | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | | 5 | Watched TV all day | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | | 6 | Walked for a hour | 2018-10-21 14:34:28 | 2018-10-21 14:34:28 | +----+------------------------+---------------------+---------------------+ 6 rows in set (0.00 sec) ``` 這是在數據庫中創建的表。 ## Sequelize `build()`和`save()` 使用`build()`和`save()`分兩步或使用`create()`一步創建新行。 `build_save.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); const note = Note.build({ description: 'Took a cold bath' }); note.save().then(() => { console.log('new task saved'); }).finally(() => { sequelize.close(); }); ``` 本示例使用`build()`和`save()`創建一個新的筆記。 ## Sequelize `findById` 使用`findById()`,我們通過其 ID 查找特定行。 `find_by_id.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); Note.findById(2).then((note) => { console.log(note.get({ plain: true })); console.log('********************') console.log(`id: ${note.id}, description: ${note.description}`); }).finally(() => { sequelize.close(); }); ``` 該示例查找帶有 ID 2 的筆記。 ```js console.log(note.get({ plain: true })); ``` 默認情況下,Sequelize 返回大量元數據。 要關閉數據,我們使用`plain: true`選項。 ```js $ node find_by_id.js { id: 2, description: 'Visited friend', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z } ******************** id: 2, description: Visited friend ``` 我們將行打印兩次。 在第一種情況下,我們返回所有數據。 在第二種情況下,我們僅選擇兩個字段。 ## Sequelize `findOne` `findOne()`方法搜索單個行。 `find_one.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); Note.findOne({ where: { id: 1 } }).then(note => { console.log(note.get({ plain: true })); }).finally(() => { sequelize.close(); }); ``` 該示例使用`find_one()`返回表的第一行。 `where`選項指定要查找的 ID。 ```js $ node find_one.js { id: 1, description: 'Tai chi in the morning', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z } ``` 這是輸出。 ## Sequelize `async`和`await` 在下一個示例中,我們使用`async`和`await`關鍵字。 `find_one2.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getOneNote() { let user = await Note.findOne(); console.log(user.get('description')); sequelize.close(); } getOneNote(); ``` 我們使用`async`和`await`關鍵字返回帶有`findOne()`的第一行。 ## Sequelize 計數 `count()`方法計算表中的行數。 `count_rows.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function countRows() { let n = await Note.count(); console.log(`There are ${n} rows`); sequelize.close(); } countRows(); ``` 該示例計算`notes`表中的行數。 ```js $ node count_rows.js There are 7 rows ``` 目前,表格中有 7 行。 ## Sequelize 刪除行 使用`destroy()`方法刪除一行。 它返回已刪除的行數。 `delete_row.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function deleteRow() { let n = await Note.destroy({ where: { id: 2 } }); console.log(`number of deleted rows: ${n}`); sequelize.close(); } deleteRow(); ``` 該示例刪除 ID 為 2 的行。 ## Sequelize 更新行 用`update()`方法更新一行。 `update_row.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function updateRow() { let id = await Note.update( { description: 'Finished reading history book' }, { where: { id: 1 } }); sequelize.close(); } updateRow(); ``` 該示例更新了第一行的描述。 ## Sequelize `findAll` `findAll()`方法搜索多個實例。 `find_all.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function findAllRows() { let notes = await Note.findAll({ raw: true }); console.log(notes); sequelize.close(); } findAllRows(); ``` 該示例使用`findAll()`從數據庫表中檢索所有行。 ```js let notes = await Note.findAll({ raw: true }); ``` `raw: true`選項關閉元數據。 ```js $ node find_all.js [ { id: 1, description: 'Finished reading history book', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T16:00:22.000Z }, { id: 2, description: 'Visited friend', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z }, { id: 3, description: 'Went to cinema', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z }, { id: 4, description: 'Listened to music', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z }, { id: 5, description: 'Watched TV all day', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z }, { id: 6, description: 'Walked for a hour', createdAt: 2018-10-21T14:34:28.000Z, updatedAt: 2018-10-21T14:34:28.000Z }, { id: 7, description: 'Took a cold bath', createdAt: 2018-10-21T14:49:51.000Z, updatedAt: 2018-10-21T14:49:51.000Z } ] ``` 該示例返回了七行。 ## Seqelize 選擇列 使用`attributes`選項,我們可以選擇要包括在查詢中的列。 `columns.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getTwoColumns() { let notes = await Note.findAll({ attributes: ['id', 'description'], raw: true }); console.log(notes); sequelize.close(); } getTwoColumns(); ``` 在示例中,我們選擇`id`和`description`列。 ```js $ node columns.js Executing (default): SELECT `id`, `description` FROM `notes` AS `notes`; [ { id: 1, description: 'Finished reading history book' }, { id: 3, description: 'Went to cinema' }, { id: 4, description: 'Listened to music' }, { id: 5, description: 'Watched TV all day' }, { id: 6, description: 'Walked for a hour' } ] ``` 這是輸出。 ## Seqelize `offset`和`limit` 使用`offset`和`limit`屬性,我們可以定義`findAll()`方法中要包括的行的初始跳過和行數。 `offset_limit.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getRows() { let notes = await Note.findAll({ offset: 2, limit: 3, attributes: ['id', 'description'], raw: true }); console.log(notes); sequelize.close(); } getRows(); ``` 該示例從第二行開始還原三行。 ```js $ node offset_limit.js [ { id: 3, description: 'Went to cinema' }, { id: 4, description: 'Listened to music' }, { id: 5, description: 'Watched TV all day' } ] ``` 這是輸出。 ## Seqelize 順序排序 為了在查詢中包含`ORDER BY`子句,我們使用`order`選項。 `order_by.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getRows() { let notes = await Note.findAll({ order: [['description', 'DESC']], attributes: ['id', 'description'], raw: true }) console.log(notes); sequelize.close(); } getRows(); ``` 在示例中,我們從表中選擇所有行,并按描述以降序對其進行排序。 ```js $ node order_by.js Executing (default): SELECT `id`, `description` FROM `notes` AS `notes` ORDER BY `notes`.`description` DESC; [ { id: 3, description: 'Went to cinema'}, { id: 5, description: 'Watched TV all day' }, { id: 6, description: 'Walked for a hour'}, { id: 2, description: 'Visited friend' }, { id: 1, description: 'Tai chi in the morning' }, { id: 4, description: 'Listened to music' } ] ``` 從輸出中我們可以看到`ORDER BY`子句已添加到查詢中。 ## Seqelize `Op.IN`運算符 使用`Op.IN`運算符,我們可以確定指定的值是否與子查詢或列表中的任何值匹配。 `operator_in.js` ```js const Sequelize = require('sequelize'); const Op = Sequelize.Op; const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getRows() { let notes = await Note.findAll({ where: { id: { [Op.in]: [3, 6] } } }); notes.forEach(note => { console.log(`${note.id}: ${note.description}`); }); sequelize.close(); } getRows(); ``` 在示例中,我們選擇與 ID 列表匹配的所有行。 ```js $ node operator_in.js 3: Went to cinema 6: Walked for a hour ``` 輸出顯示兩行:ID 為 3 和 6。 ## Seqelize `Op.between`運算符 使用`Op.between`運算符,我們可以確定指定值是否與給定范圍內的任何值匹配。 `operator_between.js` ```js const Sequelize = require('sequelize'); const Op = Sequelize.Op; const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Note = sequelize.define('notes', { description: Sequelize.STRING }); async function getRows() { let notes = await Note.findAll({ where: { id: { [Op.between]: [3, 6] } }}); notes.forEach(note => { console.log(`${note.id}: ${note.description}`); }); sequelize.close(); } getRows(); ``` 該示例使用`Op.between`運算符顯示行`3..6`。 ## Sequelize `belongsTo` Sequelize `belongsTo`在源模型和提供的目標模型之間創建一對一的關聯。 外鍵添加在源上。 `belongs_to.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Employee = sequelize.define('employees', { name: Sequelize.STRING }); let Project = sequelize.define('projects', { name: Sequelize.STRING }); Employee.belongsTo(Project); let employees = [ { name: 'Jane Brown' }, { name: 'Lucia Benner' }, { name: 'Peter Novak' } ]; sequelize.sync({ force: true }).then(() => { return Employee.bulkCreate(employees); }).then((employees) => { let works = []; let i = 0; employees.forEach(employee => { let pname = 'Project ' + String.fromCharCode('A'.charCodeAt() + i); i++; let work = Project.create({ name: pname }).then(project => { employee.setProject(project); }); works.push(work); }); Promise.all(works).then(() => sequelize.close()); console.log('finish'); }); ``` 在示例中,我們有兩個模型:`Employee`和`Project`。 我們使用`belongsTo`在兩個模型之間創建一對一關聯。 我們將數據添加到模型中。 ```js let Employee = sequelize.define('employees', { name: Sequelize.STRING }); let Project = sequelize.define('projects', { name: Sequelize.STRING }); ``` 我們定義了兩個模型。 ```js Employee.belongsTo(Project); ``` 我們在`Employee`和`Project`模型之間創建一對一關聯。 外鍵在`Employee`中生成。 ```js let employees = [ { name: 'Jane Brown' }, { name: 'Lucia Benner' }, { name: 'Peter Novak' } ]; ``` 我們將創建三名員工。 ```js let works = []; ``` `works`數組用于存儲生成的`Promise`。 ```js employees.forEach(employee => { let pname = 'Project ' + String.fromCharCode('A'.charCodeAt() + i); i++; let work = Project.create({ name: pname }).then(project => { employee.setProject(project); }); works.push(work); }); ``` 我們遍歷所有員工,并為每個員工生成一個新項目。 `setProject()`添加了一個新項目。 `Project.create()`生成一個新的`Promise`,將其添加到`works`數組中。 ```js Promise.all(works).then(() => sequelize.close()); ``` `Promise.all()`解析數組中的所有`promise`。 接下來,我們檢索聯接的數據。 當我們生成還從其他表中獲取關聯數據的查詢時,我們會渴望加載。 通過`include`選項啟用了預先加載。 `belongs_to2.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Employee = sequelize.define('employees', { name: Sequelize.STRING }); let Project = sequelize.define('projects', { name: Sequelize.STRING }); Employee.belongsTo(Project); Employee.findAll({include: [Project]}).then(employees => { employees.forEach(employee => { console.log(`${employee.name} is in project ${employee.project.name}`); }); }).finally(() => { sequelize.close(); }); ``` 該示例列出了員工及其項目。 ```js Employee.findAll({include: [Project]}).then(employees => { ``` 在查詢中,我們添加`include`選項,其中包括關聯的模型。 ```js $ node belongs_to2.js Jane Brown is in project Project A Lucia Benner is in project Project B Peter Novak is in project Project C ``` 這是輸出。 ## 雙向化一對一關系 雙向關系在兩個方向上均有效。 我們可以從源模型引用目標模型,反之亦然。 為了在模型之間創建雙向一對一關系,我們將其與`belongsTo()`和`hasOne()`映射。 `bidi_one2one.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let Employee = sequelize.define('employees', { name: Sequelize.STRING }); let Project = sequelize.define('projects', { name: Sequelize.STRING }); Employee.belongsTo(Project); Project.hasOne(Employee); Project.findAll({include: [Employee]}).then(projects => { projects.forEach(project => { console.log(`${project.name} belongs to user ${project.employee.name}`); }); }).finally(() => { sequelize.close(); }); ``` 在此示例中,我們從每個項目中檢索一名員工。 ```js Employee.belongsTo(Project); Project.hasOne(Employee); ``` 為了實現雙向關聯,我們還使用`hasOne()`映射了模型。 ```js $ node bidi_one2one.js Project A belongs to user Jane Brown Project B belongs to user Lucia Benner Project C belongs to user Peter Novak ``` 這是輸出。 ## Sequelize `hasMany` Sequelize `hasMany`在源和提供的目標之間創建多對一關聯。 外鍵添加到目標上。 `one_to_many.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let User = sequelize.define('user', { name: Sequelize.STRING, }); let Task = sequelize.define('task', { description: Sequelize.STRING, }); User.hasMany(Task); async function createTables() { await User.sync(); await Task.sync(); console.log('done'); sequelize.close(); } createTables(); ``` 首先,我們創建兩個表:`users`和`tasks`。 在第二步中,我們用數據填充表。 `one_to_many2.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let User = sequelize.define('user', { name: Sequelize.STRING }); let Task = sequelize.define('task', { description: Sequelize.STRING, }); User.hasMany(Task); let mytasks1 = [ { description: 'write memo' }, { description: 'check accounts' } ]; let mytasks2 = [ { description: 'make two phone calls' }, { description: 'read new emails' }, { description: 'arrange meeting' } ]; async function addUsersTasks() { let user1 = await User.create({ name: 'John Doe' }); let tasks1 = await Task.bulkCreate(mytasks1); await user1.setTasks(tasks1); let user2 = await User.create({ name: 'Debbie Griffin' }); let tasks2 = await Task.bulkCreate(mytasks2); await user2.setTasks(tasks2); console.log('done'); sequelize.close(); } addUsersTasks(); ``` 我們有兩個執行某些任務的用戶。 ```js let user1 = await User.create({ name: 'John Doe' }); ``` 使用`User.create()`創建一個新用戶。 ```js let tasks1 = await Task.bulkCreate(mytasks1); ``` 使用`Task.bulkCreate()`生成新任務。 ```js await user1.setTasks(tasks1); ``` 使用`setTasks()`將任務添加到用戶。 最后,我們檢索數據。 `one_to_many3.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let User = sequelize.define('user', { name: Sequelize.STRING }); let Task = sequelize.define('task', { description: Sequelize.STRING, }); User.hasMany(Task); async function showUsersTasks() { let users = await User.findAll({ include: [Task] }); users.forEach(user => { console.log(`${user.name} has tasks: `); let tasks = user.tasks; tasks.forEach(task => { console.log(` * ${task.description}`); }) }); console.log('done'); sequelize.close(); } showUsersTasks(); ``` 在示例中,我們顯示了所有用戶及其關聯的任務。 ```js let users = await User.findAll({ include: [Task] }); ``` 要啟用緊急加載,我們使用`include`選項。 急切的加載是在查詢中也檢索關聯的數據時。 ```js $ node one_to_many3.js John Doe has tasks: * write memo * check accountsDebbie Griffin has tasks: * make two phone calls * read new emails * arrange meeting done ``` 這是輸出。 ## 雙向一對多關系 雙向一對多關系在兩個方向上均有效。 為了在模型之間建立雙向的一對多關系,我們使用`hasMany()`和`belongsTo()`映射它們。 `bidi_one2many.js` ```js const Sequelize = require('sequelize'); const path = 'mysql://user12:12user@localhost:3306/mydb'; const sequelize = new Sequelize(path, { operatorsAliases: false, logging: false }); let User = sequelize.define('user', { name: Sequelize.STRING }); let Task = sequelize.define('task', { description: Sequelize.STRING }); User.hasMany(Task); Task.belongsTo(User); async function showTaskUser() { let task = await Task.findOne({ include: [User] }); console.log(`${task.description} belongs to ${task.user.name}`); sequelize.close(); } showTaskUser(); ``` 該示例從檢索的任務中獲取用戶。 ```js User.hasMany(Task); Task.belongsTo(User); ``` 為了實現雙向一對一關系,我們使用`hasMany()`和`belongsTo()`映射模型。 ```js $ node bidi_one2many.js write memo belongs to John Doe ``` 這是輸出。 在本教程中,我們使用了`Seqeulize`庫。 我們創建了一些與 MySQL 交互的命令行程序。 您可能也對以下相關教程感興趣: [Knex.js 教程](/javascript/knex/), [Node Postgres 教程](/javascript/nodepostgres/), [Lodash 教程](/javascript/lodash/),[書架教程](/javascript/bookshelf/), 或列出[所有 JavaScript 教程](/all/#js)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看