简体   繁体   中英

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.

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.

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

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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