어떤 에러인가요?
initModels 파일을 이용하여 table join을 할 때,
as 키워드를 알맞게 넣지 않았을 때 발생하는 오류입니다.
에러 메세지
Shop is associated to User using an alias.
You must use the 'as' keyword to specify the alias within your include statement.
Shop은 가명을 사용하여 User와 연결된다.
포함 문에 별칭을 지정하려면 'as' 키워드를 사용해야 합니다.
User is associated to Shop using an alias.
You've included an alias (Users),
but it does not match the alias(es) defined in your association (user).
User는 가명을 사용하여 Shop와 연관된다.
별칭('Users')을 포함했지만 연결에서 정의된 별칭(user)과 일치하지 않습니다.
에러 핸들링 방법
// init-models.js
Shop.belongsTo(User, { as: 'user', foreignKey: 'user_id' }); //자식
User.hasMany(Shop, { as: 'Shops', foreignKey: 'user_id' }); //부모
Menu.belongsTo(Shop, { as: 'shop', foreignKey: 'shop_id' }); //자식
Shop.hasMany(Menu, { as: 'Menus', foreignKey: 'shop_id' }); //부모
// controllers
await Models.Shop.findOne({
include: [
{
model: Models.User,
as: 'user',
attributes: [
'shop_name',
'shop_category',
'shop_category_city',
'master_address',
],
},
{
model: Models.Menu,
as: 'Menus',
attributes: ['image_src', 'menu_category', 'name', 'price'],
},
],
attributes: [
'business_hour',
'image_src',
'phone_number',
'holiday',
'map',
'contents',
],
});
위 코드처럼 작성의 시작이 되는 테이블을 기준으로,
부모 또는 자식을 부르고 싶을 땐 자신의 as 키워드를 사용해준다.