#sails.js
#sails.js
Вопрос:
я перехожу по этой ссылке и пытаюсь показать данные
http://sailsjs.org/documentation/concepts/models-and-orm/associations/one-way-association
но я получил сообщение об ошибке «Неизвестный столбец ‘shop.building_detail’ в ‘списке полей’ «
Это ошибка sails или я что-то сделал не так?
ниже приведен мой дизайн базы данных и мой код
Модель магазина:
module.exports = {
autoPK:false,
attributes : {
shop_id : {
primaryKey : true,
type : 'int',
unique: true,
columnName : 'shop_id'
},
shop_floor : {
type : 'string'
},
shop_room : {
type : 'string'
},
shop_build : {
type : 'int',
foreignKey:'true'
},
building_detail : {
model : 'building'
}
}
};
Построение модели:
module.exports = {
autoPK:false,
attributes : {
build_id : {
primaryKey : true,
type : 'int',
unique: true,
columnName : 'build_id'
},
build_name : {
type : 'string'
},
build_address : {
type : 'string'
},
build_latitude : {
type : 'float'
},
build_longitude : {
type : 'float'
},
build_visit_count : {
type : 'int'
},
build_status : {
type : 'string'
},
build_status_last_update_time : {
type : 'time'
}
}
};
Ответ №1:
В соответствии с вашим дизайном базы данных ваша Shop
модель может выглядеть следующим образом:
Shop.js
module.exports = {
autoPK:false,
attributes : {
shop_id : {
primaryKey : true,
type : 'int',
unique: true,
columnName : 'shop_id'
},
shop_floor : {
type : 'string'
},
shop_room : {
type : 'string'
},
shop_build : {
model: 'Building'
}
}
};
Sails.js автоматически связывается shop_build
с первичным ключом Building
модели.
При создании магазина просто укажите идентификатор здания в качестве значения для shop_build
:
Shop.create({
shop_floor: "Some floor",
shop_room: "Some room",
shop_build: 8 // <-- building with build_id 8
})
.exec(function(err, shop) { });
И когда вы выполняете запросы магазина, вы можете заполнить сведения о здании:
Shop.find()
.populate('shop_build')
.exec(function(err, shops) {
// Example result:
// [{
// shop_id: 1,
// shop_floor: 'Some floor',
// shop_room: 'Some room',
// shop_build: {
// build_id: 8,
// build_name: 'Some building',
// ...
// }
// }]
});
Более подробную информацию см. в документации Waterline по ассоциациям.
Комментарии:
1. Что, если он захочет сохранить массив shop_build как shop_build: [8, 9, 10], как этого добиться? Спасибо.
2. @noyruto88 Тогда вместо этого вы бы определили ассоциацию «один ко многим» или «многие ко многим», используя
collection
атрибут. Подробнее смотрите документацию: sailsjs.com/documentation/concepts/models-and-orm/associations и ее подстраницы.