gpt4 book ai didi

node.js - 多个模型的 Sails JS Waterline 连接

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:08 25 4
gpt4 key购买 nike

您好,我正在尝试使用填充方法连接多个表,我用谷歌搜索但找不到这样做的有效方法,我不想多次查询数据库来构建结果,是否可以使用 sails 版本“~0.10.0-rc7”来解决它我正在构建一个有数百个表的退出大项目.

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 实体并填充关联属性;

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

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

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

关于node.js - 多个模型的 Sails JS Waterline 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23932095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com