where子句包含使用sequilize的列

时间:2015-11-10 22:04:31

标签: node.js orm sequelize.js

我正在使用看起来像这样的查询

db.Spectrum.findAll({ attributes: ['title', [db.Sequelize.fn('SUM', db.Sequelize.col('quantity') ), 'count']], include: [ {model: db.Varietal, attributes : ['specID', 'id'], include : [ { model : db.Wine, required: false, attributes : ['varietal_id', 'id'], where : {restaurant_id : restaurant_id, owner_id : null} } ], } ], group : ['specID'] })

这给了我正确的结果,问题是因为它和左边的where子句连接它运行得非常慢(大约2秒)。

左连接的原始查询看起来像这样..

LEFT OUTER JOIN `wines` AS `Varietals.Wines` ON `Varietals`.`id` = `Varietals.Wines`.`varietal_id` AND `Varietals.Wines`.`restaurant_id` = 16 AND `Varietals.Wines`.`owner_id` IS NULL

我希望查询有左连接和这样的where子句..

LEFT OUTER JOIN `wines` AS `Varietals.Wines` ON `Varietals`.`id` = `Varietals.Wines`.`varietal_id` WHERE `Varietals.Wines`.`restaurant_id` = 16 AND `Varietals.Wines`.`owner_id` IS NULL

但是我尝试的所有内容都让Spectrum'在它之前然后找不到那一行。这个假设怎么做?或者我将不得不使用原始查询?

2 个答案:

答案 0 :(得分:3)

include.where将始终将条件添加到联接中。 但是在Sequelize v3.13.0中添加了对特殊嵌套键的支持。

不可能将where对象添加到包含$包含的点分隔键的顶层对象中,以指定它是嵌套字段。

将其应用于您的代码:

db.Spectrum.findAll({
  include: [
    {
      model: db.Varietal,
      include : [
        {
          model : db.Wine
        }
      ]
    }
  ],
  where: {
    '$Varietals.Wines.restaurant_id$': restaurant_id,
    '$Varietals.Wines.owner_id$': null
  },
  group : ['specID']
});

(我删除了一些关注重要部分的陈述)

答案 1 :(得分:0)

包含数组

     include = [{
        model: db.caregiverCategory,
        as: 'categories',
        attributes: ['name'],
        required: true,
        attributes: ['name'],
        include: [{
            model: db.category,
            as: 'category',
            required: true
        }]
    }]

条款在哪里

    where[Op.or] = [{
        '$categories.name$': { [Op.like]: '%' + query.category_name + '%' }
   }, {
        '$categories.category.name$': { [Op.like]: '%' + query.category_name + '%' }
    }]

您需要在属性[[name]]中添加所有名称之类的字段,例如name(在或中必填),否则将导致unknowm列错误。