在JavaScript中追加对象

4
在下面的代码中,我试图向mainQuery对象中添加populate。如果我只传递types,那么我会得到预期的结果并且查询也会构建成功。但是如果我同时传递types和子类别,则查询将会中断,并且对象不会按照下面的预期查询添加。请给出解决方案?
mainQuery = Category.find();

if(req.param('types')) {
    searchKey = "types";
    typesObj.where = {
        id: 1
    };

    mainQuery.populate(searchKey, typesObj);
}   

if(req.param('subcat')) {
    searchkeySubCat = "subcategory";
    typesSubcat.where = {
        id: 1
    };

    mainQuery.populate(searchkeySubCat, typesSubcat);
}

mainQuery.exec(function (err, category) {

});

期望的查询如下

Category.find().populate('types', {where: {id:1}}).populate('subcategory', {where: {id:1}}).exec(function (err, res) { 
    console.log(res)
})

当您在populate中删除where时会发生什么? - Makah
2个回答

2

请按以下步骤尝试:

function _getWhereClause(key, value) {
   return {where: {key: value}};
}

if (req.param('types')) {
    populateKey = 'types';
    mainQuery.populate(populateKey, _getWhereClause('id', 1));
}
// Do the same for any number of populate you want

最后执行查询:
mainQuery.exec(function (err, category) {

});

请查看文档以更好地理解- http://sailsjs.org/documentation/reference/waterline-orm/queries/populate


谢谢您的回答,我会检查并更新您。同时,您能否回答我的另一个问题,它在 Stackover flow 中可以找到下面的网址吗?http://stackoverflow.com/questions/37608302/sailsjs-using-through-relation-how-to-get-the-value-of-non-related-models - Muthukumar Marichamy

0
你正在尝试使用 mainQuery 对象进行方法链接。基本上,你正在形成一个查询,然后在以后使用该查询。我建议你将这个查询作为一个字符串。例如:
mainQuery = "Category.find().";
mainQuery+= "populate("+searchKey+","+ typesObj+").";
mainQuery +="populate("+searchkeySubCat+","+ typesSubcat+").";
mainQuery +="exec(function (err, res) { console.log(res)});";

因此,当您访问mainQuery时,您将拥有:

   Category.find().populate('types', {where:     {id:1}}).populate('subcategory', {where: {id:1}}).exec(function (err, res) { 
console.log(res)
 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接