-
항해 99 5기 TIL_73항해 99 2022. 3. 25. 04:43
▶ Today I Learned
<실전 프로젝트>
[MySQL Join된 테이블 사용]
현재 우리는 sequelize라는 ORM 프레임워크로 MySQL을 조작하고 있다.
아래는 User테이블의 join 부분
User.associate = (db) => { db.User.belongsToMany(db.Badge, { through: "UserBadge", as: "MyBadges", onDelete: "CASCADE" }); db.User.belongsTo(db.Badge, { as: "MasterBadge", foreignKey: "masterBadgeId" }); };
User와 Join된 Badge 테이블의 join 부분
Badge.associate = (db) => { db.Badge.belongsToMany(db.User, { through: "UserBadge", as: "Challengers" }); db.Badge.hasMany(db.User, { as: "MasterBadge", foreignKey: "masterBadgeId" }) };
이렇게 join 설정된 상황에서 아래와 같은 코드들을 입력해 isGivenBadge를 구하려 했다.
// 유저가 누군지 지정해주기 const thatUser = await User.findOne({ where: { id: userId, }, }); /* ch: 예시로 각각 카테고리별 시간 100시간 이상일 떄 해당 뱃지 지급한다고 가정, 기준 추후에 달라지면 각각 설정하기 위해 if (100 <= categoryTotalTime 이 구문 각각의 if 절에 넣어줌 */ // 뱃지 카테고리 종류별로 가져오기 beauty, study, sports, counsel, culture, etc let theBadge = []; if (badgeCategory === "beauty") { // Badge 테이블에 등록된 해당 뱃지 가져와야 함 theBadge = await Badge.findOne({ where: { name: "beauty", // 해당 뱃지 이름이나 id로 찾아야 함 }, }); console.log("뱃지 ------------------------------", theBadge) console.log("아이디--------------------------------------", theBadge.id) console.log("기븐 뱃지는 과연 나오나") console.log("이것이 thatUser다ㅏㅏㅏㅏㅏ", thatUser) // 그 특정 유저의 뱃지 리스트를 가져옴, user 모델에서 MyBadges로 정의된 상태 const isGivenBadge = await thatUser.getMyBadges({ where: { badgeId: theBadge.id, }, }); console.log("기븐뱃지 ----------------", isGivenBadge) console.log("11111")
하지만 콘솔창을 찍어본 결과는 아래와 같았다.
아이디-------------------------------------- 1 기븐 뱃지는 과연 나오나 이것이 thatUser다ㅏㅏㅏㅏㅏ user {
원인을 알지 못하던 도중 문득 내가 join문에 대하여 잘못 알고 있을 수도 있겠다는 생각이 들었다.
항상 컴퓨터의 잘못보다는 사용자가 무언가 잘못한 게 있기 마련.
User를 기준으로 as에 쓰인 MyBadges라는 이름을 이용해 조인된 부분을 사용할 수 있다.
(조인된 테이블은 UserBadge라는 테이블로 DB상에 나타난다.)
db.User.belongsToMany(db.Badge, { through: "UserBadge", as: "MyBadges", onDelete: "CASCADE" });
이때 해당 테이블에 접근 시 getter가 필요한데 이는 getMyBadges와 같이 사용할 수 있다.
난 처음엔 특정 유저가 join된 테이블을 통해 특정 뱃지를 가져오는 것이니 그 join테이블의 badgeId를 써야한다고 생각했다.
하지만 UserTable이라는 것은 join된 관계를 직접적으로 보여주는 것일 뿐
Badge의 아이디를 조작하려면 결국 Badge테이블의 속성을 통해 가져와야 하는 것이었다.
그래서 Badge테이블에서 뱃지를 찾는 것 처럼 badgeId -> id로 바꾸어 주었다.
const isGivenBadge = await thatUser.getMyBadges({ where: { id: theBadge.id, }, });
그랬더니 잘 작동한다.
Executing (default): SELECT `badge`.`id`, `badge`.`name`, `badge`.`desc`, `badge`.`imageUrl`, `badge`.`leftBadges`, `badge`.`createdAt`, `badge`.`updatedAt`, `UserBadge`.`createdAt` AS `UserBadge.createdAt`, `UserBadge`.`updatedAt` AS `UserBadge.updatedAt`, `UserBadge`.`userId` AS `UserBadge.userId`, `UserBadge`.`badgeId` AS `UserBadge.badgeId` FROM `badges` AS `badge` INNER JOIN `UserBadge` AS `UserBadge` ON `badge`.`id` = `UserBadge`.`badgeId` AND `UserBadge`.`userId` = 4 WHERE (`badge`.`id` = 1); 기븐뱃지 ---------------- [] 11111
https://dream-herb.tistory.com/58
+
rm -rf /tmp/mongodb-27017.sock
?authSource=admin
이런 것들은 어떤 역할일까?
MySQL에 대한 공부도 더욱 필요하다.
▶ 느낀 점
DB에 대한 공부도 생각보다 깊게할 필요가 있어보인다.
결국 정보를 가져와야 하니 사용이 필수인데 모르는 기능이 되게 많은 것 같다.
▶ 공부 시 참고 링크들
https://lgphone.tistory.com/86
https://info-lab.tistory.com/60
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_79 (0) 2022.03.30 항해 99 5기 TIL_78 (0) 2022.03.29 항해 99 5기 TIL_72 (0) 2022.03.25 항해 99 5기 TIL_71 (0) 2022.03.22 항해 99 5기 WIL_10 (0) 2022.03.20