使用 Waterline ORM 查找或创建相关实体
Finding or creating related entities with Waterline ORM
假设我有两个模型:
国家:
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
cities: {
collection: 'city',
via: 'country'
}
}
城市:
attributes: {
name: {
type: 'string',
required: true
},
country: {
model: 'country'
}
}
我想 find/create 这两个对象并将它们关联起来。这是我的代码:
Country.findOrCreate({name: object.Country}).exec(function createFindCB(error, country){
City.findOrCreate({name: object.City, country:country}).exec(function createFindCB(error, city){
console.log(city);
console.log(country);
});
});
但它不起作用。如果我用同一个城市和国家调用它 100 次,我希望数据库中只有 1 个国家实例和 1 个城市实例。虽然我确实有 1 个国家实例,但有 100 个城市实例。我做错了什么?
正确的代码应该是:
Country.findOrCreate({name: object.Country}).exec(function createFindCB(error, country){
City.findOrCreate({name: object.City, country:country.id}).exec(function createFindCB(error, city){
console.log(city);
console.log(country);
});
});
假设我有两个模型:
国家:
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
cities: {
collection: 'city',
via: 'country'
}
}
城市:
attributes: {
name: {
type: 'string',
required: true
},
country: {
model: 'country'
}
}
我想 find/create 这两个对象并将它们关联起来。这是我的代码:
Country.findOrCreate({name: object.Country}).exec(function createFindCB(error, country){
City.findOrCreate({name: object.City, country:country}).exec(function createFindCB(error, city){
console.log(city);
console.log(country);
});
});
但它不起作用。如果我用同一个城市和国家调用它 100 次,我希望数据库中只有 1 个国家实例和 1 个城市实例。虽然我确实有 1 个国家实例,但有 100 个城市实例。我做错了什么?
正确的代码应该是:
Country.findOrCreate({name: object.Country}).exec(function createFindCB(error, country){
City.findOrCreate({name: object.City, country:country.id}).exec(function createFindCB(error, city){
console.log(city);
console.log(country);
});
});