laravel - 如何在我的 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
指令?)但我不知道该怎么做。有任何想法吗?
解决方案
解决了,最后几乎太简单了。
在我的模型中,我只是在我的回报中Course
添加了一个 Eloquent :where
instances
public function instances(): HasMany
{
return $this->hasMany(Instance::class)->where('start_date','>',Carbon::now()->format('Ymd'));;
}
使用 Carbon 获取当前日期进行比较。
推荐阅读
- entity-framework - 从实体框架执行存储过程
- sql - 为什么减号而不是运算符给出不同的结果
- dataframe - Pyspark - 基于列表中的值爆炸数据框
- c - 尝试从 cs50 编译 pset2 可读性 .. 给出相同的错误“使用未声明的标识符”将不胜感激任何建议
- java - 将响应(json)映射到 java 类
- python - Python3 Openpyxl - PatternFill bgColor 不起作用?
- swiftui - Apple 文档的语法在哪里解释?(特别是 swiftUI 文档)
- node.js - MongoDB中的范围查找分页命令
- reactjs - Firebase 使用 React JS:没有 setTimeout 就无法添加文档
- macos - VSC 中 Haxe 语言支持中的悬停提示设置