【问题标题】:sequalize Search in Associationsequelize 关联搜索
【发布时间】:2017-05-05 06:21:03
【问题描述】:
using sequelize 3.30.1

我有两个模型 Category 和 Product 通过关联关联。

var Category = sequelize.define('Category',
  { name: DataTypes.STRING });

};

var Product = sequelize.define("Product", {

price:{type:DataTypes.INTEGER,UNSIGNED:true},
 {
   classMethods: {
   associate: function() {

    Product.belongsTo(Category, {
      foreignKey: {
         name: 'category',
         allowNull: false
      }
    });

 });

我如何搜索带有Category.name 的产品,例如%CatName%

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    抱歉,只需要重新格式化您的代码:

    var Category = sequelize.define('Category',
      {
        name: DataTypes.STRING
      });
    
    var Product = sequelize.define("Product",
      {
        price: {
         type: DataTypes.INTEGER,
         UNSIGNED:true
        },
        classMethods: {
          associate: function() {
            Product.belongsTo(Category, {foreignKey: {name: 'category', allowNull: false}});
          }
        }
      });
    

    现在你已经有了两个模型并定义了关联,你可以使用 findAll() 方法进行查询。

    var catName = 'book';
    
    Product.findAll({
      include : [
        {
          model: Category,
          where: {
            name: {
              $like: '%' + catName + '%'
            }
          }
        }
      ]
    })
    .then(function(
       console.log(result);
    });
    

    看看这是否有效。

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 1970-01-01
      • 2021-05-14
      • 2016-04-11
      • 2012-04-21
      • 2017-06-09
      • 2017-08-15
      • 2013-10-05
      • 2018-12-09
      相关资源
      最近更新 更多