Node.js/Sequelize

[ORM] ๐Ÿ“š Sequelize - left join ํ•˜๋Š”๋ฒ•

์ธํŒŒ_ 2021. 12. 7. 09:54

sequelize-

Sequelize left join

์‹œํ€„๋ผ์ด์ €์—์„œ include๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ inner join ์ฒ˜๋ฆฌ์ด๋‹ค.

๋‹ค์Œ ์ฝ”๋“œ๋ฅผ ๋ณด์ž.

 

[Associate ์„ค์ •]

Shop.hasMany(ShopAd, {foreignKey : 'shop_id', as : 'ads'});

ShopAd.belongsTo(Shop, {foreignKey : 'id'})

 

[ORM]

Shop.findAll({
    where: {id:shopId},
    include: [{
      model: ShopAd, 
      as: 'ads', 
      where: { is_valid: 1, is_vertify: 1 }
    }]
})

 

[SQL ๋กœ๊ทธ]

SELECT `Shop`.`id`, `Shop`.`user_id`, `Shop`.`short_name`, `Shop`.`description`, `Shop`.`tips`, `Shop`.`city`, `Shop`.`province`, `Shop`.`address`, `Shop`.`logo`, `Shop`.`publicity_photo`, `Shop`.`taobao_link`, `Shop`.`is_vertify`, `Shop`.`create_time`, `Shop`.`update_time`, `ads`.`id` AS `ads.id`, `ads`.`shop_id` AS `ads.shop_id`, `ads`.`pic_url` AS `ads.pic_url`, `ads`.`description` AS `ads.description`, `ads`.`link` AS `ads.link`, `ads`.`is_valid` AS `ads.is_valid`, `ads`.`is_vertify` AS `ads.is_vertify`, `ads`.`create_time` AS `ads.create_time`, `ads`.`update_time` AS `ads.update_time` 
FROM `weshop_shop` AS `Shop`
INNER JOIN `weshop_shop_advertsing` AS `ads` 
ON `Shop`.`id` = `ads`.`shop_id` AND `ads`.`is_valid`=1 AND `ads`.`is_vertify`=1
WHERE `Shop`.`id`='1';

 

ํ•ด๋‹น ๊ด€๊ณ„๋ฅผ include์ฒ˜๋ฆฌํ•˜์—ฌ ์ฟผ๋ฆฌ๋ฅผ ๋‚ ๋ ค๋ณด๋ฉด inner joinํ˜•ํƒœ๊ฐ€ ๋จ์„ ์•Œ์ˆ˜ ์žˆ๋‹ค.

 

๋”ฐ๋ผ์„œ left outer join ํ˜•ํƒœ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š”,  required: false  ์˜ต์…˜์„ ์ฃผ์–ด์•ผ ํ•œ๋‹ค.

Shop.findAll({
    where: {id:shopId},
    include: [{
      model: ShopAd, 
      as: 'ads', 
      where: { is_valid: 1, is_vertify: 1 },
      required: false // left outer join์ด ๋˜๊ฒŒ ํ•œ๋‹ค.
    }]
})