knex join

knex join?

knex에서 join을 사용하면 foreign key로 연결된 테이블을 연결 할 수 있습니다.

knex join query 작성 방법


sql table을 보면 chat_room을 사이로 usercitytable이 연결되어 있습니다. city.id는 chat_room.city_id와 연결되어있고 user.idchat_room.creater와 연결되어있습니다. 공통된 연결을 통하여 하나의 가상테이블을 작성 할 수 있습니다.

1
2
3
4
knex('user')
.join('chat_room', 'chat_room.creator', 'user.id')
.join('city', 'chat_room.city_id', 'city.id')
.as('temporary_table')

위 코드를 실행하면 temporary_table이라는 이름의 임시테이블이 생성됩니다.

knex join query 참조하는 방법

1
2
3
4
5
6
getAllRoomList () {
return knex('user')
.join('chat_room', 'chat_room.creator', 'user.id')
.join('city', 'chat_room.city_id', 'city.id')
.as('temporary_table')
}

위 코드를 getAllRoomList라는 함수에 저장하게 되면

1
let query = this.getAllRoomList()

위 코드와 같이 query라는 변수에 담을 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
getDataRoomList ({city_id, start_at, like, id}) {
let query = this.getAllRoomList()
if(city_id && start_at){
if(like){
query = query.where({city_id, start_at})
query = query.orderBy('like', 'desc')
}else if(id){
query = query.where({city_id, start_at})
query = query.orderBy('id', 'desc')
}
}
return query
}

따라서 연결된 테이블에서 원하는 검색 조건에 대한 결과를 갖고오길 원한다면 위 코드와 같이 합쳐진 코드의 결과를 변수에 담아두고 필터링하면 됩니다.

공유하기