【问题标题】:NodeJS+Sequelize+Jade; Using the hasMany collection on an objectNodeJS+续集+玉;在对象上使用 hasMany 集合
【发布时间】:2014-07-28 02:36:33
【问题描述】:

我正在开发一个 nodejs+sequelize+jade 网络应用程序来学习 nodejs。一切基本的东西都很清楚,但现在我想提高赌注。我有一个名为品牌的对象(表)。对象产品与品牌具有一对多的关系。我喜欢做的是找到所有品牌并在 Jade 模板中显示它们,并列出其下的产品。

这是一些基本代码

var Brand = sequelize.import(application_root + "/models/brand.js");
var Product = sequelize.import(application_root + "/models/product.js");
Brand.hasMany(Product, { as: 'Products', foreignKey: 'brand'});
Product.belongsTo(Brand, { foreignKey: 'key'});

在展示我做的品牌和产品的过程中;

  Brand.findAll().error(errorHandler).success(function(brands) 
    {   
        brands[0].getProducts().success(function(products) {
        brands[0].products = products;
        });
        res.render('listOfbrands.jade', {  title: 'List of brands', items: brands});
    });

最奇怪的是,执行 console.log 时我可以看到一个查询被触发,但它没有使用品牌的主键创建正确的查询。查询是 select * from products where "brand" 为空

我还想知道我是否正确分配子集合以通过这样做在我的 Jade 模板中访问它

ul
each item in items
li(class='brandItem')= item.name
ul 
each product in item.products
li=product.name

【问题讨论】:

    标签: node.js one-to-many pug sequelize.js


    【解决方案1】:

    我学到了两个原则; 首先要查找每个项目的子项目,必须使用 sequelize query-chainer。这使我可以查询所有内容,并在完成后将项目集合放入我的玉模板。其次使用brands.forEach 所以我的最终代码就像

     Brand.findAll().error(errorHandler).success(function(brands) 
    {   
        var chainer = new Sequelize.Utils.QueryChainer();
        brands.forEach(function(theBrand) {
            chainer.add(theBrand.getProducts({where: "brand="+theBrand.key }).error(errorHandler).success(function(products) 
            {                
                theBrand.products = products;                   
            }));
        }
        chainer.runSerially().success(function(results) {
            res.render('listOfbrands.jade', {  title: 'List of brands', items: brands});
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-01-10
      • 1970-01-01
      • 2023-01-30
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多