how can I sort by related column in laravel lighthouse graphql?
For example, I have Products that have One Category but I can’t SortBy Category. How can I do that?
GraphQL
getProducts(orderBy: _ @orderBy): [Product!]! @all
type Product {
id: ID
code: String
article: String
category: Category
}
type Category {
id: ID
name: String
products: [Product]
}
My Models where you can see the relationship between Products and Categories
class Product extends Model
{
...
public function category()
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
...
public function products()
{
return $this->hasMany(Product::class);
}
}
SOLUTION
Create a Builder
<?php
namespace AppGraphQLQueries;
use IlluminateDatabaseEloquentBuilder;
class ProductBuilder
{
public function getProducts(Builder $builder)
{
return
$builder->join('categories', 'categories.id', '=', 'products.category_id');
}
}
Then add the builder to schema.graphql
getProducts(orderBy: _ @orderBy): [Product!]!
@all
@builder(method: "App\GraphQL\Queries\ProductBuilder@getProducts")
Now you can call and order by relationship
{
getProducts(orderBy: {column: "categories.name", order: ASC}){
id
code
article
category {
name
}
}
}
2
Answers
I think the query variable part is not correct. Check this:
If:
Then Category class should look something like this:
And Product class should resemble this:
2 )Then add following to your schema.graphql.php
There was an error in my first post, it should be: @orderBy(columns: ["category"]).
Then you should be able to query: