4

With a schema like the below, is there a way to execute a query and have the results sorted by the name property of the JobType entity? I'd like to have a paginated list of jobs, and display the results sorted by the job type name, alphabetically.

extend type Query @middleware(checks: ["auth:api"]) {
    jobs(orderBy: _ @orderBy): [Job!]! @paginate(defaultCount: 10, model: "App\\Job")
}

type Job {
    id: ID!
    description: String!
    job_type: JobType! @belongsTo
}

type JobType {
    id: ID!
    name: String!
}

I've tried using the @builder directive, then using a join in the builder to bring the name property in that way, but that seems to cause some issues with entity IDs, which causes the relationships to link to the wrong things.

Any ideas?

Nathan Gaskin
  • 1,334
  • 9
  • 32

2 Answers2

3

The @builder as you mentioned is a great solution for this. The fix for the issue causing issues with the entity IDs is to pass a ->select('model.*') in your builder. That way it will just return the data of the model you asked for and still order by on the relation.

1

Just to collect the question and accepted answer into a working example, this is what ended up working for me:

GraphQL:

extend type Query @middleware(checks: ["auth:api"]) {
    jobs(@builder(method: "App\\Models\\Job@jobsInOrder")): [Job!]! @paginate(defaultCount: 10, model: "App\\Job")
}

type Job {
    id: ID!
    description: String!
    job_type: JobType! @belongsTo
}

type JobType {
    id: ID!
    name: String!
}

Job.php:

public function jobsInOrder(Builder $builder): Builder
{

    // Connect the events with their date_times
    return $builder->join('job_types', 'jobs.id', '=', 'job_types.job_id')
        ->select('jobs.*')
        ->orderBy('job_types.name');
}

Orchis
  • 296
  • 5
  • 18