[Sequelize] include[join] 시에 where 사용 방법

나랭·2024년 7월 2일
0

Include 시에 where 2가지 방법

  1. Include 내에서 where를 사용

    await User.findAll
    ({
      include: {
        model: Tool,
        as:'Instruments',
        where: {
    	    size: {
    		    [Op.ne]:'small'
    	    }
        }
      },
    });
  2. $as값.column명$ 을 Parent model의 where에 사용

    await User.findAll
    ({
      where: {
        '$Instruments.size$': { [Op.ne]:'small'},
      },
      include: {
        model: Tool,
        as:'Instruments',
      },
    });

Include 시에 sub model의 where와 무관하게 parent model의 모든 데이터 불러오기

  • required: true // where에 부합하지 않는 값을 가진 데이터는 반환하지 않도록 (기본값)
  • required: false // where에 맞지 않는 sub-model이더라도 parent model을 가져옴
const response = await UserRepo.find({
    include: [
      {
        model: db.safety_checks,
        as: "safety_checks",
        where: safetyCheckWhere,
        required: false, // safetyCheckWhere 조건에 부합하지 않더라도 모든 UserRepo의 데이터 가져오기
      },
    ],
  });
profile
안녕하세요! 나랭입니다😉

0개의 댓글