Sequelize версия: "sequelize": "^5.21.3"
. Вот рабочий пример:
index.ts
:
import { sequelize } from '../../db';
import Sequelize, { Model, DataTypes, Op } from 'sequelize';
class Category extends Model {}
Category.init(
{
id: {
primaryKey: true,
autoIncrement: true,
allowNull: false,
type: DataTypes.INTEGER,
},
name: DataTypes.STRING,
},
{ sequelize, modelName: 'categories' },
);
Category.belongsTo(Category, { foreignKey: 'parentId', as: 'parent', targetKey: 'id' });
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
const parent1 = { id: 1, name: 'Mobile' };
const parent2 = { id: 4, name: 'Kitchenware' };
await Category.bulkCreate([parent1, parent2]);
await Category.bulkCreate([
{ id: 7, name: 'Mobile Cover', parentId: parent1.id },
{ id: 8, name: 'Knife', parentId: parent2.id },
{ id: 9, name: 'Mobile Glass', parentId: parent1.id },
]);
// test
const result = await Category.findAll({
include: [
{
model: Category,
required: true,
as: 'parent',
attributes: ['id', 'name'],
},
],
attributes: ['id', 'name'],
raw: true,
});
console.log('result: ', result);
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Результаты выполнения:
Executing (default): DROP TABLE IF EXISTS "categories" CASCADE;
Executing (default): DROP TABLE IF EXISTS "categories" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "categories" ("id" SERIAL , "name" VARCHAR(255), "parentId" INTEGER REFERENCES "categories" ("id") ON DELETE SET NULL 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 = 'categories' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "categories" ("id","name") VALUES (1,'Mobile'),(4,'Kitchenware') RETURNING *;
Executing (default): INSERT INTO "categories" ("id","name","parentId") VALUES (7,'Mobile Cover',1),(8,'Knife',4),(9,'Mobile Glass',1) RETURNING *;
Executing (default): SELECT "categories"."id", "categories"."name", "parent"."id" AS "parent.id", "parent"."name" AS "parent.name" FROM "categories" AS "categories" INNER JOIN "categories" AS "parent" ON "categories"."parentId" = "parent"."id";
result: [ { id: 7,
name: 'Mobile Cover',
'parent.id': 1,
'parent.name': 'Mobile' },
{ id: 8,
name: 'Knife',
'parent.id': 4,
'parent.name': 'Kitchenware' },
{ id: 9,
name: 'Mobile Glass',
'parent.id': 1,
'parent.name': 'Mobile' } ]
Проверка записей данных в базе данных:
node-sequelize-examples=# select * from "categories";
id | name | parentId
----+--------------+----------
1 | Mobile |
4 | Kitchenware |
7 | Mobile Cover | 1
8 | Knife | 4
9 | Mobile Glass | 1
(5 rows)