74.md 29.7 KB
Newer Older
W
wizardforcel 已提交
1
# Sequelize 教程
W
wizardforcel 已提交
2 3 4 5 6

> 原文: [http://zetcode.com/javascript/sequelize/](http://zetcode.com/javascript/sequelize/)

Sequelize 教程展示了如何使用 Sequelize ORM 在 JavaScript 中对数据库进行编程。

W
wizardforcel 已提交
7
## Sequelize 
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
Sequelize 是 Node.js 的基于 Promise 的 ORM。 它可与 PostgreSQL,MySQL,SQLite 和 MSSQL 方言配合使用,并具有可靠的事务支持,关系,读取复制等功能。
W
wizardforcel 已提交
10 11 12 13 14 15 16

对象关系映射(ORM)是一种从面向对象的语言访问关系数据库的技术。

在本教程中,我们使用 MySQL。

## 设置续集

W
wizardforcel 已提交
17
我们初始化一个 Node 应用并安装 Sequelize 和 MySQL 适配器。
W
wizardforcel 已提交
18

W
wizardforcel 已提交
19
```js
W
wizardforcel 已提交
20 21 22 23 24 25 26
$ nodejs -v
v10.12.0

```

我们使用 Node 版本 10.12.0。

W
wizardforcel 已提交
27
```js
W
wizardforcel 已提交
28 29 30 31
$ npm init

```

W
wizardforcel 已提交
32
我们启动一个新的 Node 应用。
W
wizardforcel 已提交
33

W
wizardforcel 已提交
34
```js
W
wizardforcel 已提交
35 36 37 38 39 40 41
$ npm i sequelize
$ nmp i mysql2 

```

我们安装 Seqelize 和 MySQL 驱动程序。 有两个驱动程序可用:`mysql``mysql2`; 我们选择了后者。

W
wizardforcel 已提交
42
## Sequelize 认证
W
wizardforcel 已提交
43 44 45 46 47

在第一个示例中,我们创建与 MySQL 数据库的连接。

`authenticate.js`

W
wizardforcel 已提交
48
```js
W
wizardforcel 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
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 数据库时显示一条消息。

W
wizardforcel 已提交
66
```js
W
wizardforcel 已提交
67 68 69 70 71 72
const Sequelize = require('sequelize');

```

我们加载 Sequelize 模块。

W
wizardforcel 已提交
73
```js
W
wizardforcel 已提交
74 75 76 77 78 79
const path = 'mysql://user12:12user@localhost:3306/testdb';

```

这是 MySQL 连接路径。 它包含用户名,密码,主机名,数据库端口和数据库名称。

W
wizardforcel 已提交
80
```js
W
wizardforcel 已提交
81 82 83 84 85 86
const sequelize = new Sequelize(path, { operatorsAliases: false });

```

我们实例化 Sequelize。

W
wizardforcel 已提交
87
```js
W
wizardforcel 已提交
88 89 90 91 92 93
sequelize.authenticate().then(() => {
  console.log('Connection established successfully.');
...  

```

W
wizardforcel 已提交
94
`authenticate()`方法通过尝试向数据库进行认证来测试连接。 建立连接后,我们将打印一条消息。
W
wizardforcel 已提交
95

W
wizardforcel 已提交
96
```js
W
wizardforcel 已提交
97 98 99 100 101 102 103 104
}).catch(err => {
  console.error('Unable to connect to the database:', err);
...  

```

如果发生错误,我们将打印一条错误消息。

W
wizardforcel 已提交
105
```js
W
wizardforcel 已提交
106 107 108 109 110 111 112 113
}).finally(() => {
  sequelize.close();
});

```

最后,我们关闭数据库连接。

W
wizardforcel 已提交
114
```js
W
wizardforcel 已提交
115 116 117 118 119 120 121 122
$ node authenticate.js
Executing (default): SELECT 1+1 AS result
Connection established successfully

```

这是输出。 输出也包括调试输出。

W
wizardforcel 已提交
123
## Sequelize 模型定义
W
wizardforcel 已提交
124 125 126 127 128

`Model`代表数据库中的表。 此类的实例代表数据库行。 Sequelize 的`define()`方法定义了一个新模型。

`define_model.js`

W
wizardforcel 已提交
129
```js
W
wizardforcel 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
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();
})

```

该示例创建一个简单的模型。 它将模型保存到数据库表中。

W
wizardforcel 已提交
151
```js
W
wizardforcel 已提交
152 153 154 155 156 157
let Dummy = sequelize.define('dummy', {
    description: Sequelize.STRING
});

```

W
wizardforcel 已提交
158
创建了一个新模型`Dummy`。 第一个参数是型号名称。 第二个参数由属性组成,这些属性是表列。 在我们的例子中,我们有一个列名`description`,它是`String`类型。
W
wizardforcel 已提交
159

W
wizardforcel 已提交
160
```js
W
wizardforcel 已提交
161 162 163 164 165 166 167 168 169 170
Dummy.sync().then(() => {
    console.log('New table created');
}).finally(() => {
    sequelize.close();
})

```

`sync()`方法将模型同步到数据库。 实际上,它将创建一个新的`dummies`表。 (表名是复数的。)

W
wizardforcel 已提交
171
```js
W
wizardforcel 已提交
172 173 174 175 176 177 178 179 180 181 182 183
$ 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`选项将其关闭。

W
wizardforcel 已提交
184
```js
W
wizardforcel 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
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`选项将其关闭。

W
wizardforcel 已提交
200
## Sequelize 删除表
W
wizardforcel 已提交
201 202 203 204 205

`drop()`方法删除一个表。

`drop_table.js`

W
wizardforcel 已提交
206
```js
W
wizardforcel 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
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`表。

W
wizardforcel 已提交
229
## Sequelize 时间戳
W
wizardforcel 已提交
230 231 232 233 234

Sequelize 自动为模型添加时间戳。 我们可以使用`timestamps`控制此行为。

`timestamps.js`

W
wizardforcel 已提交
235
```js
W
wizardforcel 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
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();
    });
});

```

该示例创建一个没有时间戳的表。

W
wizardforcel 已提交
263
```js
W
wizardforcel 已提交
264 265 266 267 268 269 270 271 272 273 274 275
const sequelize = new Sequelize(path, {
    operatorsAliases: false,
    logging: false,
    define: {
        timestamps: false
    }
});

```

在这里,我们关闭时间戳记。

W
wizardforcel 已提交
276
```js
W
wizardforcel 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289
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)

```

我们确认表中没有时间戳。

W
wizardforcel 已提交
290
## Sequelize 批量创建
W
wizardforcel 已提交
291 292 293 294 295

`bulkCreate()`方法创建并批量插入多个实例。 该方法采用对象数组。

`bulk_create_notes.js`

W
wizardforcel 已提交
296
```js
W
wizardforcel 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
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();
    });
});

```

表格示例记录了几行。

W
wizardforcel 已提交
332
```js
W
wizardforcel 已提交
333 334 335 336 337 338 339 340 341
const sequelize = new Sequelize(path, {
    operatorsAliases: false,
    logging: false
});

```

我们禁用日志记录。

W
wizardforcel 已提交
342
```js
W
wizardforcel 已提交
343 344 345 346 347 348
sequelize.sync({ force: true }).then(() => {

```

`sqeuelize.syn()`同步所有型号。 在`force`选项丢弃的表,如果它的创建之前就存在。

W
wizardforcel 已提交
349
```js
W
wizardforcel 已提交
350 351 352 353 354 355 356 357
Note.bulkCreate(notes, { validate: true }).then(() => {
    console.log('notes created');
...    

```

`bulkCreate()`创建具有六行的表格。

W
wizardforcel 已提交
358
```js
W
wizardforcel 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
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)

```

这是在数据库中创建的表。

W
wizardforcel 已提交
376
## Sequelize `build()`和`save()`
W
wizardforcel 已提交
377 378 379 380 381

使用`build()``save()`分两步或使用`create()`一步创建新行。

`build_save.js`

W
wizardforcel 已提交
382
```js
W
wizardforcel 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
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();
});

```

W
wizardforcel 已提交
404
本示例使用`build()``save()`创建一个新的笔记。
W
wizardforcel 已提交
405

W
wizardforcel 已提交
406
## Sequelize `findById`
W
wizardforcel 已提交
407 408 409 410 411

使用`findById()`,我们通过其 ID 查找特定行。

`find_by_id.js`

W
wizardforcel 已提交
412
```js
W
wizardforcel 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
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();
});

```

W
wizardforcel 已提交
435
该示例查找带有 ID 2 的笔记。
W
wizardforcel 已提交
436

W
wizardforcel 已提交
437
```js
W
wizardforcel 已提交
438 439 440 441 442 443
console.log(note.get({ plain: true }));

```

默认情况下,Sequelize 返回大量元数据。 要关闭数据,我们使用`plain: true`选项。

W
wizardforcel 已提交
444
```js
W
wizardforcel 已提交
445 446 447 448 449 450 451 452 453 454 455 456
$ 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

```

我们将行打印两次。 在第一种情况下,我们返回所有数据。 在第二种情况下,我们仅选择两个字段。

W
wizardforcel 已提交
457
## Sequelize `findOne`
W
wizardforcel 已提交
458 459 460 461 462

`findOne()`方法搜索单个行。

`find_one.js`

W
wizardforcel 已提交
463
```js
W
wizardforcel 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
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。

W
wizardforcel 已提交
486
```js
W
wizardforcel 已提交
487 488 489 490 491 492 493 494 495 496
$ 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 }

```

这是输出。

W
wizardforcel 已提交
497
## Sequelize `async`和`await`
W
wizardforcel 已提交
498 499 500 501 502

在下一个示例中,我们使用`async``await`关键字。

`find_one2.js`

W
wizardforcel 已提交
503
```js
W
wizardforcel 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
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()`的第一行。

W
wizardforcel 已提交
530
## Sequelize 计数
W
wizardforcel 已提交
531 532 533 534 535

`count()`方法计算表中的行数。

`count_rows.js`

W
wizardforcel 已提交
536
```js
W
wizardforcel 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
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`表中的行数。

W
wizardforcel 已提交
562
```js
W
wizardforcel 已提交
563 564 565 566 567 568 569
$ node count_rows.js
There are 7 rows

```

目前,表格中有 7 行。

W
wizardforcel 已提交
570
## Sequelize 删除行
W
wizardforcel 已提交
571 572 573 574 575

使用`destroy()`方法删除一行。 它返回已删除的行数。

`delete_row.js`

W
wizardforcel 已提交
576
```js
W
wizardforcel 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
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 的行。

W
wizardforcel 已提交
602
## Sequelize 更新行
W
wizardforcel 已提交
603 604 605 606 607

`update()`方法更新一行。

`update_row.js`

W
wizardforcel 已提交
608
```js
W
wizardforcel 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
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();

```

该示例更新了第一行的描述。

W
wizardforcel 已提交
634
## Sequelize `findAll`
W
wizardforcel 已提交
635 636 637 638 639

`findAll()`方法搜索多个实例。

`find_all.js`

W
wizardforcel 已提交
640
```js
W
wizardforcel 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
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()`从数据库表中检索所有行。

W
wizardforcel 已提交
666
```js
W
wizardforcel 已提交
667 668 669 670 671 672
let notes = await Note.findAll({ raw: true });

```

`raw: true`选项关闭元数据。

W
wizardforcel 已提交
673
```js
W
wizardforcel 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
$ 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 } ]

```

该示例返回了七行。

W
wizardforcel 已提交
708
## Seqelize 选择列
W
wizardforcel 已提交
709 710 711 712 713

使用`attributes`选项,我们可以选择要包括在查询中的列。

`columns.js`

W
wizardforcel 已提交
714
```js
W
wizardforcel 已提交
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
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`列。

W
wizardforcel 已提交
739
```js
W
wizardforcel 已提交
740 741 742 743 744 745 746 747 748 749 750 751
$ 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' } ]

```

这是输出。

W
wizardforcel 已提交
752
## Seqelize `offset`和`limit`
W
wizardforcel 已提交
753 754 755 756 757

使用`offset``limit`属性,我们可以定义`findAll()`方法中要包括的行的初始跳过和行数。

`offset_limit.js`

W
wizardforcel 已提交
758
```js
W
wizardforcel 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
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();

```

该示例从第二行开始还原三行。

W
wizardforcel 已提交
787
```js
W
wizardforcel 已提交
788 789 790 791 792 793 794 795 796
$ node offset_limit.js
[ { id: 3, description: 'Went to cinema' },
  { id: 4, description: 'Listened to music' },
  { id: 5, description: 'Watched TV all day' } ]

```

这是输出。

W
wizardforcel 已提交
797
## Seqelize 顺序排序
W
wizardforcel 已提交
798 799 800 801 802

为了在查询中包含`ORDER BY`子句,我们使用`order`选项。

`order_by.js`

W
wizardforcel 已提交
803
```js
W
wizardforcel 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
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();

```

在示例中,我们从表中选择所有行,并按描述以降序对其进行排序。

W
wizardforcel 已提交
832
```js
W
wizardforcel 已提交
833 834 835 836 837 838 839 840 841 842 843 844
$ 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`子句已添加到查询中。

W
wizardforcel 已提交
845
## Seqelize `Op.IN`运算符
W
wizardforcel 已提交
846 847 848 849 850

使用`Op.IN`运算符,我们可以确定指定的值是否与子查询或列表中的任何值匹配。

`operator_in.js`

W
wizardforcel 已提交
851
```js
W
wizardforcel 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
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 列表匹配的所有行。

W
wizardforcel 已提交
882
```js
W
wizardforcel 已提交
883 884 885 886 887 888 889 890
$ node operator_in.js
3: Went to cinema
6: Walked for a hour

```

输出显示两行:ID 为 3 和 6。

W
wizardforcel 已提交
891
## Seqelize `Op.between`运算符
W
wizardforcel 已提交
892 893 894 895 896

使用`Op.between`运算符,我们可以确定指定值是否与给定范围内的任何值匹配。

`operator_between.js`

W
wizardforcel 已提交
897
```js
W
wizardforcel 已提交
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
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();

```

W
wizardforcel 已提交
926
该示例使用`Op.between`运算符显示行`3..6`
W
wizardforcel 已提交
927

W
wizardforcel 已提交
928
## Sequelize `belongsTo`
W
wizardforcel 已提交
929 930 931 932 933

Sequelize `belongsTo`在源模型和提供的目标模型之间创建一对一的关联。 外键添加在源上。

`belongs_to.js`

W
wizardforcel 已提交
934
```js
W
wizardforcel 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
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`在两个模型之间创建一对一关联。 我们将数据添加到模型中。

W
wizardforcel 已提交
987
```js
W
wizardforcel 已提交
988 989 990 991 992 993 994 995 996 997 998 999
let Employee = sequelize.define('employees', {
    name: Sequelize.STRING
});

let Project = sequelize.define('projects', {
    name: Sequelize.STRING
});

```

我们定义了两个模型。

W
wizardforcel 已提交
1000
```js
W
wizardforcel 已提交
1001 1002 1003 1004 1005 1006
Employee.belongsTo(Project);

```

我们在`Employee``Project`模型之间创建一对一关联。 外键在`Employee`中生成。

W
wizardforcel 已提交
1007
```js
W
wizardforcel 已提交
1008 1009 1010 1011 1012 1013 1014 1015
let employees = [
    { name: 'Jane Brown' }, { name: 'Lucia Benner' }, { name: 'Peter Novak' }
];

```

我们将创建三名员工。

W
wizardforcel 已提交
1016
```js
W
wizardforcel 已提交
1017 1018 1019 1020
let works = [];

```

W
wizardforcel 已提交
1021
`works`数组用于存储生成的`Promise`
W
wizardforcel 已提交
1022

W
wizardforcel 已提交
1023
```js
W
wizardforcel 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
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);

});

```

W
wizardforcel 已提交
1040
我们遍历所有员工,并为每个员工生成一个新项目。 `setProject()`添加了一个新项目。 `Project.create()`生成一个新的`Promise`,将其添加到`works`数组中。
W
wizardforcel 已提交
1041

W
wizardforcel 已提交
1042
```js
W
wizardforcel 已提交
1043 1044 1045 1046
Promise.all(works).then(() => sequelize.close());

```

W
wizardforcel 已提交
1047
`Promise.all()`解析数组中的所有`promise`
W
wizardforcel 已提交
1048 1049 1050 1051 1052

接下来,我们检索联接的数据。 当我们生成还从其他表中获取关联数据的查询时,我们会渴望加载。 通过`include`选项启用了预先加载。

`belongs_to2.js`

W
wizardforcel 已提交
1053
```js
W
wizardforcel 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
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();
});

```

该示例列出了员工及其项目。

W
wizardforcel 已提交
1085
```js
W
wizardforcel 已提交
1086 1087 1088 1089 1090 1091
Employee.findAll({include: [Project]}).then(employees => {

```

在查询中,我们添加`include`选项,其中包括关联的模型。

W
wizardforcel 已提交
1092
```js
W
wizardforcel 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
$ 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

```

这是输出。

## 双向化一对一关系

W
wizardforcel 已提交
1104
双向关系在两个方向上均有效。 我们可以从源模型引用目标模型,反之亦然。 为了在模型之间创建双向一对一关系,我们将其与`belongsTo()``hasOne()`映射。
W
wizardforcel 已提交
1105 1106 1107

`bidi_one2one.js`

W
wizardforcel 已提交
1108
```js
W
wizardforcel 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
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();
});

```

在此示例中,我们从每个项目中检索一名员工。

W
wizardforcel 已提交
1141
```js
W
wizardforcel 已提交
1142 1143 1144 1145 1146 1147 1148
Employee.belongsTo(Project);
Project.hasOne(Employee);

```

为了实现双向关联,我们还使用`hasOne()`映射了模型。

W
wizardforcel 已提交
1149
```js
W
wizardforcel 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158
$ 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

```

这是输出。

W
wizardforcel 已提交
1159
## Sequelize `hasMany`
W
wizardforcel 已提交
1160 1161 1162 1163 1164

Sequelize `hasMany`在源和提供的目标之间创建多对一关联。 外键添加到目标上。

`one_to_many.js`

W
wizardforcel 已提交
1165
```js
W
wizardforcel 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
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`

W
wizardforcel 已提交
1202
```js
W
wizardforcel 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
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();

```

我们有两个执行某些任务的用户。

W
wizardforcel 已提交
1252
```js
W
wizardforcel 已提交
1253 1254 1255 1256 1257 1258
let user1 = await User.create({ name: 'John Doe' });

```

使用`User.create()`创建一个新用户。

W
wizardforcel 已提交
1259
```js
W
wizardforcel 已提交
1260 1261 1262 1263 1264 1265
let tasks1 = await Task.bulkCreate(mytasks1);

```

使用`Task.bulkCreate()`生成新任务。

W
wizardforcel 已提交
1266
```js
W
wizardforcel 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
await user1.setTasks(tasks1);

```

使用`setTasks()`将任务添加到用户。

最后,我们检索数据。

`one_to_many3.js`

W
wizardforcel 已提交
1277
```js
W
wizardforcel 已提交
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
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();

```

在示例中,我们显示了所有用户及其关联的任务。

W
wizardforcel 已提交
1320
```js
W
wizardforcel 已提交
1321 1322 1323 1324 1325 1326
let users = await User.findAll({ include: [Task] });

```

要启用紧急加载,我们使用`include`选项。 急切的加载是在查询中也检索关联的数据时。

W
wizardforcel 已提交
1327
```js
W
wizardforcel 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
$ 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`

W
wizardforcel 已提交
1345
```js
W
wizardforcel 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
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();

```

该示例从检索的任务中获取用户。

W
wizardforcel 已提交
1379
```js
W
wizardforcel 已提交
1380 1381 1382 1383 1384 1385 1386
User.hasMany(Task);
Task.belongsTo(User);

```

为了实现双向一对一关系,我们使用`hasMany()``belongsTo()`映射模型。

W
wizardforcel 已提交
1387
```js
W
wizardforcel 已提交
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
$ 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)