Мои модели:
const Offer = sequelize.define("Offer", {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
image: {
type: DataTypes.STRING,
allowNull: false,
},
partner: {
type: DataTypes.STRING,
allowNull: false,
},
});
const Vertical = sequelize.define("Vertical", {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
});
const OfferVertical = sequelize.define("OfferVertical", {});
// Определение связей
Offer.belongsToMany(Vertical, {
through: OfferVertical,
foreignKey: "offerId",
as: "Verticals",
});
Vertical.belongsToMany(Offer, {
through: OfferVertical,
foreignKey: "verticalId",
as: "Offers",
});
Функция для заполнения данными базы данных
async function populateTables(data) {
try {
await sequelize.transaction(async (transaction) => {
for (const offerData of data) {
const { verticals, ...offer } = offerData;
const createdOffer = await Offer.create(offer, { transaction });
const createdVerticals = await Vertical.bulkCreate(verticals, {
transaction,
});
await createdOffer.setVerticals(createdVerticals, { transaction });
}
});
console.log("Данные успешно добавлены");
} catch (error) {
console.error("Ошибка при добавлении данных:", error);
}
}
Заполняю тестовыми данными:
const offersData = [
{
title: "Offer 1",
image: "https://example.com/image1.png",
partner: "Partner 1",
verticals: [{ title: "Nutra" }, { title: "Gambling" }, { title: "FB" }],
},
{
title: "Offer 2",
image: "https://example.com/image2.png",
partner: "Partner 2",
verticals: [{ title: "Gambling" }, { title: "Mobile" }],
},
];
populateTables(offersData);
И пытаюсь отфильтровать по полю verticals:
const offers = await Offer.findAll({
include: [
{
model: Vertical,
as: "Verticals",
through: {
attributes: [],
},
where: {
title: "Mobile",
},
},
],
});
и мне выдает данные так:
{
"id": "b5661611-b600-4b8e-98d6-eb8ee897b0ca",
"title": "Offer 2",
"image": "https://example.com/image2.png",
"partner": "Partner 2",
"createdAt": "2023-06-21T06:12:15.000Z",
"updatedAt": "2023-06-21T06:12:15.000Z",
"Verticals": [
{
"id": "eb972f22-f415-4b28-bd18-dc57c7b6abf9",
"title": "Mobile",
"createdAt": "2023-06-21T06:12:15.000Z",
"updatedAt": "2023-06-21T06:12:15.000Z"
}
]
}
а надо чтобы вот так:
{
"id": "b5661611-b600-4b8e-98d6-eb8ee897b0ca",
"title": "Offer 2",
"image": "https://example.com/image2.png",
"partner": "Partner 2",
"createdAt": "2023-06-21T06:12:15.000Z",
"updatedAt": "2023-06-21T06:12:15.000Z",
"Verticals": [
{
"id": "8a6fe619-a0d6-4c95-ae0d-574475d6196d",
"title": "Gambling",
"createdAt": "2023-06-21T06:12:15.000Z",
"updatedAt": "2023-06-21T06:12:15.000Z"
},
{
"id": "eb972f22-f415-4b28-bd18-dc57c7b6abf9",
"title": "Mobile",
"createdAt": "2023-06-21T06:12:15.000Z",
"updatedAt": "2023-06-21T06:12:15.000Z"
}
]
}
Как это сделать?