sequelize关联查询的分页问题,join,limit

2019-02-27  本文已影响0人  AsaGuo

需求:

select * 
  from product 
  join product
    on product.id=place.productid 
   and place.city=1100 
 where product.price>100 
 limit 10

错误写法:

models.product.findAll({
   where: ["price>=?", 100 ],
   include: [{
       model:models.product,
       where: { city:1100 }
   }],
   limit:12
})
// 生成的sql语句中,分页限制错误
select product.*, place.* 
 from (select * 
 from product 
where product.price>100 
limit 10) 
 join place 
   on product.id=place.productid 
  and place.city=1100

正确一(required:true):

models.product.findAll({
    where: ["price>=?", 100 ],
    include: [{
        model:models.product,
        where: { city:1100 },
        required:true  //inner join方式
    }],
    limit:10,
})

// 结果:
select product.*,place.* 
  from product 
  join place 
    on product.id=place.productid 
   and place.city=1100 
 where product.price>100 
 limit 10

正确二(subQuery:false):

// 备注:这样对于只含一个include关联的查询倒是问题不大,如果include多个对象,关联的对象有1对多,多对多的关系,就不好控制了。
models.product.findAll({
    where: ["price>=?", 100 ],
    include: [{
        model:models.product,
        where: { city:1100 }
    }],
    limit:10,
    subQuery:false   //不让在子查询里分页,全局处理
})
上一篇下一篇

猜你喜欢

热点阅读