Sails JS Waterlinejoin了多个模型

您好我试图join多个表与填充方法,我GOOGLE了,找不到有效的方式做到这一点,我不想查询数据库多次build立的结果,是否有可能解决这个问题与帆版本“ 〜0.10.0-rc7“我正在build造一个有超过一百张桌子的大型项目。

var co = { adapter: 'someMysqlServer', migrate:'safe', autoCreatedAt: false, autoUpdatedAt: false, autoPK:false, attributes:{ id:{ type:"int", primaryKey: true, autoIncrement: true }, code:"string", priority :"int", co_group_c_id :"int", timezone_c_id :"int", lang_c_id :"int", currency_c_id :"int", name_used :"string", name_official :"string", co_tax_no :"int", co_vat_no :"int", co_vat_reg :"int", co_reg_record :"string", co_representative :"string", co_addresses:{ collection: "co_address", via: "co_user_id" }, } }; module.exports = co; var co_address = { adapter: 'someMysqlServer', migrate:'safe', autoCreatedAt: false, autoUpdatedAt: false, autoPK:false, attributes: { id:{ type:"int", primaryKey: true, autoIncrement: true, }, address_c_id:"int" , address_street_first: "string", address_street_second: "int", address_street_third: "int", address_postalcode: "string", address_city: "string", co_user_id: { model: 'co_user' }, co_id: { model: 'co' }, co_address_opening_hours:{ collection: "co_address_opening_hours", via: "co_address_id" }, } }; module.exports = co_address; var co_address_opening_hours = { adapter: 'someMysqlServer', migrate:'safe', autoCreatedAt: false, autoUpdatedAt: false, autoPK:false, attributes:{ id:{ type:"int", primaryKey: true, autoIncrement: true }, day_c_id: "int", time_from: "datetime", time_to :"datetime", co_address_id: { model: 'co_address' } } }; module.exports = co_address_opening_hours; //controller get_co:function(req,res){ co.find() .populate("co_addresses") .populate("co_address_opening_hours") .exec(function(e, company) { if(e) console.log(e); console.log(company); res.json(company); }) 

在SailsJS 0.10+中,您可以使用模型关联来执行数据库连接。 你可以在这里阅读更多关于它们: http : //sailsjs.com/documentation/concepts/models-and-orm/associations

基本上你首先在你的模型中定义一个关联;

 var someModel = { attributes: { name: { type: 'text' } } }; var someOtherModel = { attributes: { name: { type: 'text' }, associationProp: { model: 'someModel' } } }; 

在上面的代码someOtherModel包含关联(关系) someModel 。 要执行连接查询,可以使用.populate()方法。 例如检索所有其他模型实体并填充关联属性;

 someOtherModel.find().populate('associationProp').exec(...); 

对于MySQL和PSQL适配器,还有.query()方法可用,您可以在其中编写一些手写的SQL查询来执行(这也适用于sails <0.10)。

 Model.query(<sql query>, <optional data>, callback);