簡體   English   中英

sequelize, Statement(where) in statement(where)

[英]sequelize, Statement(where) in statement(where)

我試圖用 2 個小時來解決一個不是一個問題的小問題。 我在一個生成的自耕農 Angular-fullstack 應用程序上。

我想用 sequelize 編寫此代碼:

SELECT * 
FROM demand 
WHERE city_id NOT IN (
SELECT city_id
FROM demand
WHERE user_id=req.params.user_id)

我還有以下代碼,但這不起作用。 我只得到 []

export function getCity(req, res) {
  return Demand.findAll({
    where: {
      city_id:{ $notIn: Demand.findAll({
        attributes: ['city_id'],
        where: {
          user_id: req.params.user_id,
        }
      })}
    }
  })
  .then(handleEntityNotFound(res))
  .then(respondWithResult(res))
  .catch(handleError(res));
}

你有線索嗎? 謝謝。

第一個查詢的問題是因為 sequelize 的 findall 方法返回一個承諾。

在帶有 sequelize 的 where 條件中使用子查詢的唯一方法是通過字面量方法: sequelize.literal('your query');

檢查此問題以獲取更多信息https://github.com/sequelize/sequelize/issues/3961

我還沒有找到一個很好的解決方案:我終於寫了查詢。

export function showDemandArtistNoUser(req, res) {
  return db.sequelize.query('SELECT * FROM demands WHERE city_id NOT IN (SELECT city_id FROM demands WHERE user_id='+req.params.user_id+')', { type: db.sequelize.QueryTypes.SELECT })
  .then(handleEntityNotFound(res))
  .then(respondWithResult(res))
  .catch(handleError(res));
}

使用我的 angular-fullstack,我必須在我的頁面上添加:

 import db from '../../sqldb';

我在我的項目中遇到了類似的問題。 我選擇實現它的方式有點不同,原因有兩個:

  1. 如果在某個時間點 Sequelize 決定實現子查詢 - 語法准備好了。
  2. 對 SQL 注入使用 Sequelize 保護。

這是我的代碼片段,希望它有所幫助。

const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{
    attributes: ['fkey'],
    where: {
         field1: 1,
         field2: 2,
         field3: 3
    }})
    .slice(0,-1); // to remove the ';' from the end of the SQL

MyTable.find( {
    where: {
        id: {
             $notIn: sequelize.literal('(' + tempSQL + ')'),
        }
    } 
} );

有些人可能會選擇不使用 tempSQL 變量,而只是在 find 結構中構建 SQL(也許使用輔助方法?)

我也認為這可能是 sequelize 子查詢擴展的基礎,因為它幾乎使用相同的語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM