model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
import { gql } from '@apollo/client';
import { useQuery } from '@apollo/client';
const GET_USER_AND_POSTS = gql`
query getUserAndPosts($id: Int!) {
user(where: { id: $id }) {
id
name
posts {
id
title
content
published
}
}
}
`;
const UserPage = ({ userId }) => {
const { data, loading, error } = useQuery(GET_USER_AND_POSTS, {
variables: { id: userId },
});
if (loading) return Loading...
;
if (error) return Error :(
;
const { user } = data;
return (
{user.name}
{user.posts.map((post) => (
{post.title}
{post.content}
{post.published ? 'Published' : 'Draft'}
))}
);
};
在上面的代码中,我们手动获取了查询用户及其所有的帖子,并将结果渲染到页面上。虽然这种方法可能需要更多的代码,但它