2016-05-24 6 views
4

私のコードの下に、私はmainQueryオブジェクトにそのオブジェクトを追加しようとします。型だけを渡すと、期待した結果が得られ、クエリもビルドされます。タイプとサブカテゴリの両方を渡すと、クエリが壊れてオブジェクトが期待されるクエリごとに追加されません。親切にこれを解決する方法は?javascriptのオブジェクトを追加します

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) { 

}); 

期待クエリ何あなたがトラインされていることは基本的にmainQueryオブジェクトに連鎖する方法である

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

内部の場所を削除するとどうなりますか? – Makah

答えて

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) { 

}); 

をチェック詳細は012を参照してください。

+0

あなたの答えをありがとう、私はあなたを確認し、更新されます。その間、Stackoverのフローにある私の別の質問に答えることができますか? http://stackoverflow.com/questions/37608302/sailsjs-using-through-relation-how-to-get-the-value-of-non-related-models –

0

次のように。したがって基本的に1つのクエリーを形成し、後でそのクエリーを使用します。このクエリを文字列として作成することをお勧めします。例えば、 。

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) 
}); 
関連する問題