在过去的几个小时里,我一直在用头撞墙,但找不到解决问题的方法。在我的 sails 模型中,我有 2 个一对多关联。 “A”模型可以有多个“B”,“B”模型可以有多个“C”。在我的 Controller 中,当我执行 a.find().populate('b') (...)
时,它会返回 A 模型的整个集合,但仅填充 A 模型的每个条目一个 B,它与我的数据库(mysql)中的当前数据集不匹配。并且不会填充 B 模型中的 C 条目。换句话说,我正在努力实现诸如嵌套人口之类的目标。
Controller 代码有问题吧?我怎样才能做到这一点?
提前致谢!
编辑:
Company.js
module.exports = {
identity: 'company',
attributes: {
name: {
type: 'string',
required: true
},
address: {
type: 'string',
required: true
},
zip_code: {
type: 'string',
required: true
},
city: {
type: 'string',
required: true
},
nif: {
type: 'integer',
required: true,
minLength: 9
},
country: {
type: 'string',
required: true
},
phone_number: {
type: 'string',
required: true
},
email: {
type: 'email',
required: true
},
facilities: {
collection: 'facility',
references: 'facility',
on: 'id',
via: 'company'
}
}
};
设施.js
module.exports = {
identity: 'facility',
attributes: {
company: {
columnName: 'id_company',
model: 'company'
},
warehouses: {
collection: 'warehouse',
references: 'warehouse',
on: 'id',
via: 'facility'
},
name: {
type: 'string',
required: true
},
address: {
type: 'string',
required: true
},
zip_code: {
type: 'string',
required: true
},
city: {
type: 'string',
required: true
},
country: {
type: 'string',
required: true
},
phone_number: {
type: 'string',
},
email: {
type: 'email',
},
longitude: {
type: 'float',
},
latitude: {
type: 'float'
}
}
};
仓库.js
module.exports = {
identity: 'warehouse',
attributes: {
facility: {
columnName: 'id_facility',
model: 'facility',
},
name: {
type: 'string',
required: true
},
longitude: {
type: 'float',
},
latitude: {
type: 'float'
}
}
};
MainController的相关代码:
companies: function(req, res) {
company.find().populate('facilities').exec(function(err, comp){
var error = '';
if(err){
error = 'Unable to retrieve the requested information. Try again later and, if the problem persists, contact the platform administrator.';
} else if(!comp[0]) {
error = 'There\'s no company data inserted.';
}
// (...)
});
},
最佳答案
您应该从模型中删除references
和on
。
关于嵌套人口,正如我在评论中所说,Waterline 目前不支持它。您可以查看Waterline2正如他们所说,这提供了嵌套填充的可能性,但不建议用于生产。
否则你可以看看这个:Sails.js populate nested associations
关于mysql - sails/水线填充未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428624/