должно работать. Вот рабочий пример использования "sequelize": "^5.21.3"
:
import { sequelize } from '../../db';
import { DataTypes } from 'sequelize';
import assert from 'assert';
const Test = sequelize.define(
'Test',
{
testId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
isInt: true,
},
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
userId: {
type: DataTypes.INTEGER,
},
},
{ tableName: 'tests' },
);
const User = sequelize.define(
'User',
{
userId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
isInt: true,
},
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
},
{ tableName: 'users' },
);
Test.belongsTo(User, { as: 'User', foreignKey: 'userId', targetKey: 'userId' });
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
await Test.create(
{ username: 'vans', User: { username: 'nike', createdAt: new Date() } },
{ include: [{ model: User, as: 'User' }] },
);
// test
const result = await Test.findAll({
limit: 1,
include: [
{
model: User,
as: 'User',
},
],
});
console.log(result);
assert.equal(result.length, 1, 'should query one data row');
assert.equal(result[0].testId, 1);
assert.equal(result[0].username, 'vans');
assert.equal(result[0].userId, 1);
assert.equal(result[0].User.userId, 1);
assert.equal(result[0].User.username, 'nike');
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Результаты выполнения:
Executing (default): INSERT INTO "users" ("userId","username","createdAt") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "tests" ("testId","username","userId") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): SELECT "Test"."testId", "Test"."username", "Test"."userId", "User"."userId" AS "User.userId", "User"."username" AS "User.username", "User"."createdAt" AS "User.createdAt" FROM "tests" AS "Test" LEFT OUTER JOIN "users" AS "User" ON "Test"."userId" = "User"."userId" LIMIT 1;
[ Test {
dataValues: { testId: 1, username: 'vans', userId: 1, User: [User] },
_previousDataValues: { testId: 1, username: 'vans', userId: 1, User: [User] },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: true,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
tableName: 'tests',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Array],
includeNames: [Array],
includeMap: [Object],
includeValidated: true,
attributes: [Array],
raw: true },
isNewRecord: false,
User:
User {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } } ]
строк данных в базе данных:
=# select * from tests;
testId | username | userId
--------+----------+--------
1 | vans | 1
(1 row)
node-sequelize-examples=# select * from users;
userId | username | createdAt
--------+----------+----------------------------
1 | nike | 2020-03-11 07:12:24.782+00
(1 row)
исходный код: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59653217