首页 > 解决方案 > 如何在我的 Laravel 模型中“预过滤”数据?

问题描述

我正在使用 Laravel + Lighthouse PHP (GraphQL) 来获取instances与培训课程相关的日期列表 ( ):

架构:

type Query{
    course(slug: String! @eq): Course @find
}

type Course{
    id: ID!
    title: String!
    instances(
          "Order by date"
          orderBy: [OrderByClause!] @orderBy
        ): [Instance!] @hasMany
}

要求:

/graphql?query=query+{course(slug:"${this.$route.params.slug}"){
                title,
                instances(orderBy:[{field:"start_date",order: ASC}]){
                    id,
                    start_date,
                    end_date,
                    price,
                }
            }

这很好用,但它会返回任何给定课程的所有日期。我想要的是过滤掉过去的日期,这显然是无用的。因为我使用的是graphQL,所以我没有控制器,所以我假设我需要在我的模型中添加某种getter函数来过滤掉过去的日期,然后通过graphQL访问该函数(也许是Lighthouse的@method指令?)但我不知道该怎么做。有任何想法吗?

标签: laraveleloquentgraphql

解决方案


解决了,最后几乎太简单了。

在我的模型中,我只是在我的回报中Course添加了一个 Eloquent :whereinstances

public function instances(): HasMany
    {
        return $this->hasMany(Instance::class)->where('start_date','>',Carbon::now()->format('Ymd'));;
    }

使用 Carbon 获取当前日期进行比较。


推荐阅读