3

我是 GraphQL 的新手,我正在尝试进行这样的查询

{
   user(username: "Jon") { 
     name
     last_lame
     username
     posts(in_draft : true) { 
       title
       text
       in_draft
       update_at      
     }
   }
}

我想过滤用户在草稿中的帖子列表

我可以进行查询的唯一方法是通过模型的关系,但无法过滤草稿中的帖子。一对多

class User(Base):
  __tablename__ = 'user'
  id = Column(Integer, primary_key=True)
  name = Column(String)
  last_lame = Column(String)
  username = Column(String)


class Post(Base):
  __tablename__ = 'post'
  id = Column(Integer, primary_key=True)
  title = Column(String)
  text = Column(String)
  in_draft = Column(Boolean) 
  post_id = Column(Integer, ForeignKey('user.id'))

  posts = relationship("User", backref='posts')

有了这种关系,我用“backref = 'posts'”显示帖子节点

我的对象:

class User(SQLAlchemyObjectType):
  """User Object."""
  class Meta:
    model = UserModel
    interfaces = (relay.Node, )


class Post(SQLAlchemyObjectType):
  """Post Object."""
   class Meta:
      model = PostModel
      # interfaces = (relay.Node, )

询问:

class Query(graphene.ObjectType):

    user = graphene.Field(lambda: User, username=graphene.String())
    def resolve_user(self, info, username):
       query = User.get_query(info)
       return query.filter(UserModel.username == username).first()

我想让帖子的查询属于用户

   posts = graphene.List(lambda: Post, in_draft=graphene.Boolean())
   def resolve_posts(self, info, in_draft):
      query = Post.get_query(info)
      return query.filter(PostModel.in_draft == in_draft).all()

schema = graphene.Schema(
   query=Query,
   types=[User, Post])

有什么想法或建议吗?

4

1 回答 1

5

User老实说,鉴于和之间的关系Post已经定义,我将创建一个解析器来让这些组合结果同时传递两个参数,如下所示:

class Query(graphene.ObjectType):
    filter_user_posts = graphene.List(
        lambda: User,
        username=graphene.String,
        in_draft=graphene.Boolean,
    )
    def resolve_filter_user_posts(
        self, info, username, in_draft
    ):
        query = User.get_query(info=info)
        query = query.join(User.posts)
        query = query.filter(User.username == username)
        query = query.filter(Post.in_draft == in_draft)

        objs = query.all()

        return objs

然后您可以像这样简单地查询:

{
 filterUserPosts(username: "Jon", in_draft: true) { 
   name
   last_lame
   username
   posts{ 
     title
     text
     in_draft
     update_at      
   }
 }
}
于 2018-04-14T10:42:08.333 回答