I'm working on a nodejs+sequelize+jade web-app to learn nodejs. Everything basic is quite clear but now I want to up the ante. I have object(table) called brand. The object product has a one-to-many relation with brand. What I like to do is to findAll brands and show them in a Jade-template and also list the products under it.
Here is some basic code
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'});
In the route for showing the brands and products I do;
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});
});
The strangest thing is that I can see a query being fired when the console.log has been executed but it doesn't create a correct query with the primary key of the brand. The query being select * from products where "brand" is null
Also I want to know if I'm assigning the sub collection correct to access it in my Jade template by doing like this
ul
each item in items
li(class='brandItem')= item.name
ul
each product in item.products
li=product.name
There are two principles which I have learned; First to look up the sub-items of each item the sequelize query-chainer must be used. This allows me to query it all and after it finishes put the item collection to my jade template. Second to use the brands.forEach So my final code is like
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});
}
});