Skip to content

Better alternative for @whereConditions/@orderBy #1782

@LastDragon-ru

Description

@LastDragon-ru

I'm tried to use the existing @whereConditions, unfortunately, I very fast found that it is a bit strange and doesn't allow you to control available relations and their properties + it uses Mixed type that makes queries unsafe (eg "string < 10" probably is an error). Initially, I wanted to create a PR with fixes, but I carried away and created two new directives instead 😁

Will be glad for any feedback :)

@searchBy

scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

type Query {
  users(where: UsersQuery @searchBy): ID! @all
  comments(where: CommentsQuery @searchBy): ID! @all
}

input UsersQuery {
  id: ID!
  name: String!
}

input CommentsQuery {
  text: String!
  user: UsersQuery
  date: Date
}

That's all, just search 😃

# Write your query or mutation here
query {
  # WHERE name = "LastDragon"
  users(where: {
    name: {eq: "LastDragon"}
  }) {
    id
  }

  # WHERE name != "LastDragon"
  users(where: {
    name: {eq: "LastDragon", not: yes}
  }) {
    id
  }

  # WHERE name = "LastDragon" or name = "Aleksei"
  users(where: {
    anyOf: [
      {name: {eq: "LastDragon"}}
      {name: {eq: "Aleksei"}}
    ]
  }) {
    id
  }

  # WHERE NOT (name = "LastDragon" or name = "Aleksei")
  users(where: {
    anyOf: [
      {name: {eq: "LastDragon"}}
      {name: {eq: "Aleksei"}}
    ]
    not: yes
  }) {
    id
  }

  # WHERE date IS NULL
  users(where: {
    date: {isNull: yes}
  }) {
    id
  }

  # Relation: WHERE EXIST (related table)
  comments(where: {
    user: {
      where: {
        date: {between: {min: "2021-01-01", max: "2021-04-01"}}
      }
    }
  }) {
    id
  }

  # Relation: WHERE COUNT (related table) = 2
  comments(where: {
    user: {
      where: {
        date: {between: {min: "2021-01-01", max: "2021-04-01"}}
      }
      eq: 2
    }
  }) {
    id
  }
}

@sortBy

Very close to @orderBy but in addition allows using HasOne/BelongTo relations for ordering 😊

type Query {
  users(order: UsersSort @sortBy): ID! @all
  comments(order: CommentsSort @sortBy): ID! @all
}

input UsersSort {
  id: ID!
  name: String!
}

input CommentsSort {
  text: String
  user: UsersSort
}
query {
  # ORDER BY user.name ASC, text DESC
  comments(order: [
    {user: {name: asc}}
    {text: desc}
  ])
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionRequires input from multiple people

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions