Laravel lighthouse Graphql 按模型上的方法过滤

Laravel lighthouse Graphql filter by method on model

我想根据我模型上的方法过滤我的数据:

我模型中的方法:

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

和我的 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
}

但它不起作用,它说 isBatched 归档不存在,知道吗?

@eq 指令适用于列的数据库,不适用于模型的方法。所以,你可以做的一件事就是使用 Eloquent 的作用域,比如

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);
    }
}

然后,您的架构将像

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

正确的方法:

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