2016-11-10 107 views
0

嘗試使用內置ORM便利性的sequelize包括具有原始PostGIS查詢的語法。如何使用sequelize執行原始PostGIS查詢使用包括

此調用正確聯接相關promotionImage和類別表只是因爲我需要它,但它並不地理查詢我的數據庫就像我需要它:正確

promotion.findAll({ 
    include: [{ 
     model: promotionImage 
    }, { 
     model: category 
    }] 
    }).then(promoters => { 
    res.json(promoters) 
    }).catch(err => { 
    console.log('ERROR: ', err) 
    }) 

在另一方面,這種查詢發現所提供的緯度/經度範圍內的「促銷活動」,但它不能正常參加相關promotionImage和類別表:

const query = '\ 
     SELECT * \ 
     FROM "promotions" \ 
     WHERE "promotions"."location" && ST_MakeEnvelope(:southWestLng, :southWestLat, :northEastLng, :northEastLat)' 
    replacements = { 
     southWestLng, 
     southWestLat, 
     northEastLng, 
     northEastLat 
    } 

    db.sequelize.query(query, { 
    replacements, 
    type: sequelize.QueryTypes.SELECT, 
    model: promotion, 
    include: [{ 
     model: promotionImage 
    }, { 
     model: category 
    }] 
    }).then(promoters => { 
    res.json(promoters) 
    }).catch(err => { 
    console.log('ERROR: ', err) 
    }) 

有沒有辦法既查詢使用ST_MakeEnvelope語法和包括從數據其他型號sequelize和postGIS?

回答

1

Sequelize.query()不支持include,您可以使用Sequelize.fn()findAll

promotion.findAll({ 
    where: { 
     location: { 
      $overlap: db.sequelize.fn('ST_MakeEnvelope', southWestLng, southWestLat, northEastLng, northEastLat) 
     } 
    }, 
    include: [{ 
     model: promotionImage 
    }, { 
     model: category 
    }] 
    }).then(promoters => { 
    res.json(promoters) 
    }).catch(err => { 
    console.log('ERROR: ', err) 
    }) 
+0

它看起來像你的回答讓我很接近。但它沒有返回任何結果。我認爲問題在於postGIS查詢不應該有'='符號,而是'&&'。所以你的答案格式化查詢:'WHERE「promotion」。「location」= ST_MakeEnvelope(...'當它應該是:WHERE「promotions」。「location」&& ST_MakeEnvelope(...' – Scott

+1

我錯過了,我編輯了我的答案@Scott –