【问题标题】:Laravel lighthouse Graphql filter by method on modelLaravel lighthouse Graphql 按模型上的方法过滤
【发布时间】:2021-12-07 13:22:25
【问题描述】:

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

我的模型中的方法:

// . . .
    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 归档不存在,知道吗?

【问题讨论】:

    标签: laravel graphql laravel-lighthouse


    【解决方案1】:

    @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
    }
    
    

    【讨论】:

      【解决方案2】:

      正确的方法:

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

      【讨论】:

        猜你喜欢
        • 2020-10-22
        • 2020-04-18
        • 2023-02-13
        • 2021-10-22
        • 1970-01-01
        • 2019-02-03
        • 2021-02-18
        • 1970-01-01
        • 2019-11-28
        相关资源
        最近更新 更多