Sequelize - 当你有值时如何从相关 table 获取 id
Sequelize - how to get id from related table when you have the value
我的任务是使用 sequelize 将数据输入到数据库中(我对 sequelize 不太熟悉,但我已经阅读了很多关于如何使用它的资料)。
递给我的数据是这样的
//product - single, or an array
{title: 'some title', status: 'somestatus', type: 'sometype', ...}
已经设置了 producttype
和 productstatus
的一对多关系。
要使用原始 sql 将产品输入到产品 table 我将使用子查询获取 "somestatus"
和 "sometype"
的 ID 并输入 ID产品 statusId
和 typeId
列中的数字'
当我只有值时检索相关 table 行的 ID 的最佳方法是什么?
输入数据我有以下内容
Product.create({
title: 'some title',
status: 'somestatus'// Need to get id and replace it with
type: 'sometype'// Need to get id and replace it with
})
我在想什么..但在其他帮助网站上找不到类似的东西
Product.create({
title: 'some title',
status: await ProductStatus.findAll({where: {status: 'somestatus'}) // OR
type: await sequelize.literal(`SELECT id FROM producttypes WHERE type = 'sometype'` )
})
您需要对状态和类型使用 findOne
才能获取某些记录:
// you need to take into account cases when a status or a type is not found
// caution: passed values to find a status and a type should be unique
const status = await ProductStatus.findOne({where: {status: 'somestatus'})
const type = await ProductType.findOne({where: {type: 'sometype'})
const newProduct = await Product.create({
title: 'some title',
status: status.id,
type: type.id
})
//if you use router in express
router.get("/byId/:id", async (req, res) => {
const id = req.params.id;
const post = await Posts.findByPk(id); OR
//const post = await Posts.findOne({where : {id : id}})
res.json(post);
});
我的任务是使用 sequelize 将数据输入到数据库中(我对 sequelize 不太熟悉,但我已经阅读了很多关于如何使用它的资料)。
递给我的数据是这样的
//product - single, or an array
{title: 'some title', status: 'somestatus', type: 'sometype', ...}
已经设置了 producttype
和 productstatus
的一对多关系。
要使用原始 sql 将产品输入到产品 table 我将使用子查询获取 "somestatus"
和 "sometype"
的 ID 并输入 ID产品 statusId
和 typeId
列中的数字'
当我只有值时检索相关 table 行的 ID 的最佳方法是什么?
输入数据我有以下内容
Product.create({
title: 'some title',
status: 'somestatus'// Need to get id and replace it with
type: 'sometype'// Need to get id and replace it with
})
我在想什么..但在其他帮助网站上找不到类似的东西
Product.create({
title: 'some title',
status: await ProductStatus.findAll({where: {status: 'somestatus'}) // OR
type: await sequelize.literal(`SELECT id FROM producttypes WHERE type = 'sometype'` )
})
您需要对状态和类型使用 findOne
才能获取某些记录:
// you need to take into account cases when a status or a type is not found
// caution: passed values to find a status and a type should be unique
const status = await ProductStatus.findOne({where: {status: 'somestatus'})
const type = await ProductType.findOne({where: {type: 'sometype'})
const newProduct = await Product.create({
title: 'some title',
status: status.id,
type: type.id
})
//if you use router in express
router.get("/byId/:id", async (req, res) => {
const id = req.params.id;
const post = await Posts.findByPk(id); OR
//const post = await Posts.findOne({where : {id : id}})
res.json(post);
});