Я прочитал Создание с ассоциациями do c. Использование "sequelize": "^5.21.3"
В документации приведен пример сопоставления, подобный следующему:
Product.User = Product.belongsTo(User);
User.Addresses = User.hasMany(Address);
Создайте строки данных с сопоставлением следующим образом:
return Product.create({
title: 'Chair',
user: {
firstName: 'Mick',
lastName: 'Broadstone',
addresses: [{
type: 'home',
line1: '100 Main St.',
city: 'Austin',
state: 'TX',
zip: '78704'
}]
}
}, {
include: [{
association: Product.User,
include: [ User.Addresses ]
}]
});
Интересно, есть ли конкретная причина присвоить возвращаемое значение Product.belongsTo(User)
для Product.User
?
Я делаю демонстрацию, подобную этой:
const ProductBelongsToUser = Product.belongsTo(User);
const UserHasManyAddress = User.hasMany(Address);
Интеграционные тесты:
const addresses = [{ type: 'home', line1: '100 Main St.', city: 'Austin', state: 'TX', zip: '78704' }];
const user = { firstName: 'Mick', lastName: 'Broadstone', addresses };
beforeEach(async () => {
await sequelize.sync({ force: true });
});
afterAll(async () => {
await sequelize.close();
});
it('should create product, user and address with IncludeOptions.association', async () => {
const product: Product = await Product.create(
{ title: 'Chair', user },
{ include: [{ association: ProductBelongsToUser, include: [{ association: UserHasManyAddress }] }] },
);
const userModel: User = await product.getUser();
expect(userModel.firstName).toBe(user.firstName);
expect(userModel.lastName).toBe(user.lastName);
expect(userModel.addresses).toBeUndefined();
const addressModels: Address[] = await userModel.getAddresses();
expect(addressModels).toHaveLength(addresses.length);
// query user with address data rows
const userModelIncludeAddresses = await product.getUser({ include: [{ model: Address }] });
expect(userModelIncludeAddresses.firstName).toBe(user.firstName);
expect(userModelIncludeAddresses.lastName).toBe(user.lastName);
expect(userModelIncludeAddresses.addresses).toHaveLength(addresses.length);
});
Я использую ProductBelongsToUser
и UserHasManyAddress
вместо Product.User
и User.Addresses
в параметрах include
при создании строк данных.
Результаты теста:
PASS src/examples/associations/creating-with-associations/index.test.ts (6.006s)
associations
cerate with associations
✓ should create product, user and address with IncludeOptions.model (537ms)
✓ should create product, user and address with IncludeOptions.association (195ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 6.101s
Проверка строки данных в базе данных:
node-sequelize-examples=# select * from products;
id | title | createdAt | updatedAt | userId
----+-------+----------------------------+----------------------------+--------
1 | Chair | 2020-01-22 12:37:18.921+00 | 2020-01-22 12:37:18.921+00 | 1
(1 row)
node-sequelize-examples=# select * from users;
id | firstName | lastName | createdAt | updatedAt
----+-----------+------------+----------------------------+----------------------------
1 | Mick | Broadstone | 2020-01-22 12:37:18.925+00 | 2020-01-22 12:37:18.925+00
(1 row)
node-sequelize-examples=# select * from addresses;
id | type | line1 | line2 | city | state | zip | createdAt | updatedAt | userId
----+------+--------------+-------+--------+-------+-------+----------------------------+----------------------------+--------
1 | home | 100 Main St. | | Austin | TX | 78704 | 2020-01-22 12:37:18.939+00 | 2020-01-22 12:37:18.939+00 | 1
(1 row)
Это также отлично работает, даже если мне не нравился пример, приведенный в документации.