简体   繁体   English

使用外键在Sequelize ORM中进行MySQL查询

[英]MySQL query in Sequelize ORM with foreign key

I have this query, 我有这个查询,

UPDATE physics_tbls SET Level_id = (SELECT level_id FROM level_tbl WHERE Level = 'Higher') WHERE id = 192;

which I need to find the Sequelize equivalent for. 我需要找到等效的Sequelize。

So to explain, I have a table physics_tbls in which there is a field Level_id which has a foreign key to the field Level in another table called level_tbls. 因此,为了解释,我有一个表physics_tbls,其中有一个字段Level_id,该字段在另一个名为level_tbls的表中具有指向字段Level的外键。

When I update Level_id I need to do a SELECT on 'Higher' in the level_tbls table to see what id should go in for Level_id 当我更新Level_id时,我需要在level_tbls表的'Higher'上执行SELECT,以查看应该为Level_id输入什么ID

Should I be using 'through' as here ? 我应该在这里使用“直通”吗?

I can't make much sense of this 我不能做出太大的意义

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks, 谢谢,

Follow on question: Using a raw SQL query with Sequelize ORM and literal 遵循以下问题: 将原始SQL查询与Sequelize ORM和文字一起使用

Use raw queries 使用原始查询

sequelize.query("UPDATE physics_tbls SET Level_id = (SELECT level_id FROM level_tbl WHERE Level = 'Higher') WHERE id = 192;").then(([results, metadata]) => {
  // Results will be an empty array and metadata will contain the number of affected rows.
})

or 要么

A subquery can be done like this... 可以这样子查询...

physics_tbls.update(
    { Level_id : [clout.sequelize.literal("SELECT level_id FROM level_tbl WHERE Level = 'Higher'"))] }, 
    { where: { _id: 192 } }
).then(result => handleResult(result))
 .catch(err => handleError(err)) 

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM