DEV Community

Beaver Bridge
Beaver Bridge

Posted on

Sequelize의 include 안에서 order 적용하기

팀의 사용자를 불러올 때 이렇게 했는데, 결과도 로그에 찍히는 sql에도 order by 가 없다.

const { data } = await db.teams.findAll({
  include: { model: db.users, as: "users", order: [["sort_weight"]] }
});
Enter fullscreen mode Exit fullscreen mode

찾아보니 이렇게 include 안쪽이 아닌 같은 레벨에서 처리하는 거였다.

const { data } = await db.teams.findAll({
  include: { model: db.users, as: "users" },
  order: [[db.users, "sort_weight", "asc"]],
});
Enter fullscreen mode Exit fullscreen mode

만약 더 깊이 들어간다면, 다른 방법을 써야한다.

const { data } = await db.teams.findAll({
  include: { 
    model: db.users, 
    as: "users",
    include: {
      model: db.teams, 
      as: "child_teams",
      include: {
        model: db.users, 
        as: "users",
      }
    }
 },
  order: [
    [db.users, "sort_weight", "asc"],
    [sequelize.col("child_teams.users.sort_weight", "asc")],
  ],
});
Enter fullscreen mode Exit fullscreen mode

이런 식으로 sequelize.col 을 사용해서 컬럼에 직접 접근해서 사용해줘야 했다.

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay