Home > Enterprise >  Laravel lighthouse Graphql filter by method on model
Laravel lighthouse Graphql filter by method on model

Time:10-21

I want to filter my data, base on a method on my model:

method in my model:

// . . .
    public function isBatched(): bool
    {
        return $this->rows()->count() > 1;
    }

and my qraphql:

type Invoice
{
    globalId: ID! @globalId @method(name: "getKey")
    localId: Int! @method(name: "getKey")
    pdfUrl: String @method(name: "getPdfUrl")
    number: String
    poNumber: String @rename(attribute: "po_number")
    deposit: Deposit @hasOne
    rows: [InvoiceRow!] @hasMany
    bills: [Bill!] @belongsToMany(type: "paginator", relation: "bills")
    isBatched: Boolean! @method(name: "isBatched")
    isCompleted: Boolean @method(name: "isPaid")
    dueDate: DateTime @rename(attribute: "due_date")
    total: Money @method(name: "totalAmountMoney")
}

extend type Query {
    invoices: Invoice! @paginate @cache
    invoicesb(isBatched: Boolean @eq): [Invoice]! @paginate
}

but it does not work, it says isBatched filed is not exist, any idea?

CodePudding user response:

@eq directive works for column's databases, not for your model's method. So, one thing you can do is to use Eloquent's scopes, like

class Invoice extends Model 
{
    // ...
    public function scopeIsBatched(Builder $query, bool $isBatched): Builder
    {
         // Find the way to filter by your relationship count. 
         // So far, I think something like:
         return $query->withCount('rows')->where('rows_count', '>', 1);
    }
}

Then, your schema will be like

extend type Query {
    invoicesb(isBatched: Boolean @scope): [Invoice]! @paginate
}

CodePudding user response:

the right way:

public function scopeIsBatched(Builder $query, bool $isBatched): Builder
{
    if ($isBatched) {
        return $query->withCount('rows')->having('rows_count', '>', 1);
    }
    return $query;
}
  • Related