- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前,我使用 Node Js 13 和 ORM Sequelize v5 以及 ES6 中的所有这些(通过 package.json 中的“type”:“module”)实现了一个 API。
在这个项目中,当我尝试使用关联时出现问题。
我有三个相关的模型:author.js、authorbook.js 和 book.js。
作者.js:
import Sequelize from 'sequelize';
import AuthorBook from './authorbook.js';
import dotenv from 'dotenv';
dotenv.config();
const sequelize = new Sequelize(
process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
host: process.env.DB_HOST,
dialect: 'mysql'
}
);
export default class Author extends Sequelize.Model {}
Author.init({
firstName: {
firstName: false,
type: Sequelize.STRING(100)
},
lastName: {
allowNull: false,
type: Sequelize.STRING(100)
}
}, { sequelize });
Author.hasMany(AuthorBook, {
onUpdate: 'CASCADE'
});
import Sequelize from 'sequelize';
import AuthorBook from './authorbook.js';
import dotenv from 'dotenv';
dotenv.config();
const sequelize = new Sequelize(
process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
host: process.env.DB_HOST,
dialect: 'mysql'
}
);
export default class Book extends Sequelize.Model {}
Book.init({
title: {
firstName: false,
type: Sequelize.STRING(100)
}
}, { sequelize });
Book.hasMany(AuthorBook, {
onUpdate: 'CASCADE'
});
import Sequelize from 'sequelize';
import Author from './author.js';
import Book from './book.js';
import dotenv from 'dotenv';
dotenv.config();
const sequelize = new Sequelize(
process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
host: process.env.DB_HOST,
dialect: 'mysql'
}
);
export default class AuthorBook extends Sequelize.Model {}
AuthorBook.init({
authorId: {
type: Number,
allowNull: false
},
bookId: {
type: Number,
allowNull: false
},
}, { sequelize });
AuthorBook.belongsTo(Author, { foreignKey: 'authorId'});
AuthorBook.belongsTo(Book, { foreignKey: 'bookId'});
node src/server.js
时遇到的错误:
(node:23142) ExperimentalWarning: The ESM module loader is experimental.
file:///Users/alexandre/Documents/project/server/src/db/models/.js:18
Author.hasMany(AuthorBook, {
^
ReferenceError: Cannot access 'AuthorBook' before initialization
at file:///Users/alexandre/Documents/project/server/src/db/models/author.js:38:22
at ModuleJob.run (internal/modules/esm/module_job.js:110:37)
at async Loader.import (internal/modules/esm/loader.js:176:24)
最佳答案
该错误意味着您的模块之间存在循环引用。您应该将模型放在像 index.ts
这样的模块中。并在这里建立关联。请注意我的文件目录结构:
例如。./models/book.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class Book extends Sequelize.Model {}
Book.init(
{
title: {
allowNull: false,
type: Sequelize.STRING(100),
},
},
{ sequelize, modelName: 'books' },
);
./models/author.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class Author extends Sequelize.Model {}
Author.init(
{
firstName: {
allowNull: false,
type: Sequelize.STRING(100),
},
lastName: {
allowNull: false,
type: Sequelize.STRING(100),
},
},
{ sequelize, modelName: 'authors' },
);
./models/authorbook.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class AuthorBook extends Sequelize.Model {}
AuthorBook.init(
{
authorId: {
type: Sequelize.INTEGER,
allowNull: false,
},
bookId: {
type: Sequelize.INTEGER,
allowNull: false,
},
},
{ sequelize, modelName: 'authorbooks' },
);
./models/index.ts
:
import Author from './author';
import Book from './book';
import AuthorBook from './authorbook';
Author.hasMany(AuthorBook, {
onUpdate: 'CASCADE',
});
Book.hasMany(AuthorBook, {
onUpdate: 'CASCADE',
});
AuthorBook.belongsTo(Author, { foreignKey: 'authorId' });
AuthorBook.belongsTo(Book, { foreignKey: 'bookId' });
export { Author, Book, AuthorBook };
index.ts
:
import { Author, AuthorBook, Book } from './models';
import { sequelize } from '../../db';
import faker from 'faker';
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
const author = await Author.create({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
});
const book = await Book.create({
title: faker.lorem.words(3),
});
await AuthorBook.create({ authorId: author.id, bookId: book.id });
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "authors" ("id" SERIAL , "firstName" VARCHAR(100) NOT NULL, "lastName" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authors' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "books" ("id" SERIAL , "title" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'books' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "authorbooks" ("id" SERIAL , "authorId" INTEGER NOT NULL REFERENCES "authors" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "bookId" INTEGER NOT NULL REFERENCES "books" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authorbooks' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "authors" ("id","firstName","lastName") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "books" ("id","title") VALUES (DEFAULT,$1) RETURNING *;
Executing (default): INSERT INTO "authorbooks" ("id","authorId","bookId") VALUES (DEFAULT,$1,$2) RETURNING *;
node-sequelize-examples=# select * from "authors";
id | firstName | lastName
----+-----------+----------
1 | Laron | Deckow
(1 row)
node-sequelize-examples=# select * from "books";
id | title
----+-------------------------
1 | facilis molestias sequi
(1 row)
node-sequelize-examples=# select * from "authorbooks";
id | authorId | bookId
----+----------+--------
1 | 1 | 1
(1 row)
"sequelize": "^5.21.3"
,
postgres:9.6
关于javascript - [NodeJs][Sequelize] ReferenceError : Cannot access 'ModelName' before initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163520/
我正在关注 Sequelize 纪录片。在 Model Definition 部分的底部,我想知道 sequelize 变量用于什么?我可以删除它吗? { sequelize, modelNa
我有这个原始 SQL 查询。 SELECT restaurants.name AS restaurant, ROUND((6371 * ACOS(COS(RADIANS(6.9271)
我有一个 postgres 数据库,我正在使用 Sequelize。从表 车辆 和 预订 我试图在给定开始日期和结束日期的情况下获得所有可用车辆。 如果我使用给定日期搜索 Bookings: Book
我正在尝试使用 HapiJS 和 Sequelize 开始一个项目,并且开始时,希望在没有 Sequelize CLI 的情况下使事情正常工作,以了解一切是如何结合在一起的。 我见过多个示例项目,例如
sequelize init:models 命令会创建一个“models”文件夹并添加一个 index.js。 有人能解释一下这个 index.js 文件到底做了什么,以及它如何适应 Sequeliz
查看此 Sequelize tutorial 中的 models/blog.js 定义. module.exports = (sequelize, type) => { return sequ
我收到一个错误 No overload matches this call 每当我尝试使用 @HasMany() 或 @BelongsTo 装饰器时。 我正在使用 nestjs/sequelize:
const gamem = await gamemodes.findAll({attributes: ['name']}); const newme = await gamemodes.fin
我们如何使用 sequelize 4.2 创建由所有模型应用/继承的自定义实例方法?在 Sequelize 3 中,我们曾经在扩展到所有其他模型的主模型的“定义”部分中有一个“instanceMeth
我正在使用 Typescript、NodeJS 和sequelize-auto-ts 进行模型生成。我想要放置包含查找查询的两个模型给了我错误的结果,这又是由于触发了错误的查询。这是有问题的两个模型;
假设我在用户表中有 5 列 name email state isOnline createdAt | N
我有两张表,其中一张表具有另一张表的 ID。 1:1 关系。 所以像 EventFeedback somePrimaryKey userEventID UserEvent us
如何使用对象创建具有现有关联的条目? 例如, User.create({ socialMedia: [{ socialId: 1, //should reference existing
如何创建在创建 Sequelize 模型的新实例时以编程方式生成的默认值?我已经在某处阅读了如何执行此操作,但在任何地方都找不到。我以为这与classMethods有关,但我不知道应该调用什么方法。
当我设置关联时,有没有办法使用 Sequelize (sequelizejs.com) 输出所有在对象上神奇创建的函数。 例如;我有一个用户模型,我设置 User.belongsToMany(User
我该如何制作 Music是`音乐? { id: 4 name: "playlist 1" created_at: "2015-04-21T21:43:07.000Z" updated_
我可以使用 sequelize 从可用模型创建数据库模式吗?我在一个缺少许多迁移且没有测试的项目上工作。要运行测试,我需要创建一个新的 db (sqlite3),但我无法使用迁移初始化其架构(因为它们
我有一个与其他模型相关联的简单 Sequelize 模型。 module.exports = function (sequelize, DataTypes) { var Votes = seque
我有一个像这样设置的协会: m.User.hasMany(m.Interests, { joinTableName: 'user_interests', foreignKey: 'user_id' }
我有以下型号: var User = Seq.define('user', { firstName: { type: Sequelize.STRING,
我是一名优秀的程序员,十分优秀!