我正在使用Sequelize ORM并希望发布帖子请求以创建我称之为“卡片”的内容。例如,帖子请求的主体将如下所示:
{
"card": {"title": "cardTitle", "link": "cardLink", "categoryId": 1, "userId": 1},
"tags": [{"title": "tagA", "userId": 1}, {"title": "tagB", "userId": 1}, {"title": "tagC", "userId": 1}]
}
发表这篇文章后(在创建功能中),我希望返回完整的卡片列表,如列表功能中所示。我不知道如何做到这一点,特别是因为我正在迭代每张卡以创建一个m:m连接。请参阅下面的控制器。谢谢!
const Card = require('../models').card;
const Tag = require('../models').tag;
const CardTag = require('../models').card_tag;
const Category = require('../models').category;
module.exports = {
create(req, res) {
Promise.all([
Card.create(
{
title: req.body.card.title,
link: req.body.card.link,
categoryId: req.body.card.categoryId,
userId: req.body.card.userId
},
{returning: true}
),
Tag.bulkCreate(req.body.tags, {returning: true})
])
.then(([Card, Tag]) =>
Tag.map(tag =>
CardTag.create({cardId: Card.id, tagId: tag.id})
),
// How do I instead list all the Cards, just like I do in the list function below?
res.status(201).send({message: "Card created"})
)
.catch(error => res.status(400).send(error));
},
list(req, res) {
return Card
.findAll({
attributes: ['id', 'title', 'link', 'createdAt', 'updatedAt'],
include: [
{model: Category, attributes: ['title']},
{model: Tag, as: 'tag', attributes: ['title'], through: {attributes: []}}
]})
.then(cards => res.status(200).send(cards))
.catch(error => res.status(400).send(error));
}
};
型号:
卡:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Card = sequelize.define('card', {
title: {
type: DataTypes.STRING,
allowNull: false
},
link: {
type: DataTypes.STRING,
allowNull: false
},
categoryId: {
type: DataTypes.INTEGER,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
}
});
Card.associate = (models) => {
Card.belongsToMany(models.tag, {through: 'card_tag', as: 'tag'});
Card.belongsTo(models.category);
Card.belongsTo(models.user);
};
return Card;
};
card_tag:
'use strict';
module.exports = function(sequelize, DataTypes) {
const CardTag = sequelize.define('card_tag', {
cardId: DataTypes.INTEGER,
tagId: DataTypes.INTEGER
});
return CardTag;
};
类别:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('category', {
title: {
type: DataTypes.STRING,
allowNull: false
}
});
Category.associate = (models) => {
};
return Category;
};
标签:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Tag = sequelize.define('tag', {
title: {
type: DataTypes.STRING,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
}
});
Tag.associate = (models) => {
Tag.belongsToMany(models.card, { through: 'card_tag', as: 'card'});
Tag.belongsTo(models.user);
};
return Tag;
};