followers User[] @relation("FollowRelation",references: [id])
following User[] @relation("FollowRelation",references: [id])
User model 에 relation 관계를 명시해준다.
following을 증가 시키면 자동적으로 followers도 올라간다.
await client.user.update({
where: {id: loggedInUser.id},
data: {
following: {
connect: {
username,
},
},
},
});
connect 키워드로 다른 객체와 연결시켜준다.
어떤 정보를 기준으로 연결시켜줄 지는 유니크로 설정한 필드를 이용해서 연결 시켜야 한다.
const user = await client.user.findUnique({
where: {username},
// 원하는 관계에 대한 정보를 갖고 올 수 있음
include: {
following: true,
followers: true,
},
});
연결된 두 객체를 해재할때는 disconnect를 사용하면 된다.
await client.user.update({
where: {id: loggedInUser.id},
data: {
following: {
disconnect: {
username,
},
},
},
});
const aFollowers = await client.user.findUnique({
where: {username},
}).followers();
// relation 된 객체를 체이닝으로 찾을 수 있다.
const b = await client.user.findMany({
where: {following: {some: {username}}},
});
// none : 필더 조건에 매치되는 모든 관계값을 제외하고 리턴
// every :필터되는 요소에 완전히 부합되는 모든 관계값을 리턴
// some : 필터링되는 요소에 하나 이상이 부합되는 값을 리턴
const followers = await client.user
.findUnique({
where: {username},
})
.followers({
take: 5,
skip: (page - 1) * 5,
});
const totalFollowers = await client.user.count({
where: {following: {some: {username}}},
});
return {
ok: true,
followers,
totalPages: Math.ceil(totalFollowers / 5),
};
await client.user.findUnique({
where: {username},
select: {id: true},
});
// 유저 전체를 가져오지 않고 select로 id만 가져온다
const following = await client.user
.findUnique({
where: {username},
})
.following({
take: 5,
skip: 1 ,
cursor: {id: lastId}}),
});
return {
ok: true,
following,
};