为什么我不能在 Vapor 4 的自定义控制器中使用过滤器?

Why can't I use filter in custom controller with Vapor 4?

我想添加一个路由来通过搜索特定的字符串来获取匹配的数据。我在 routes.swift.

中将路线添加到 routes(_:)
import Fluent
import Vapor

func routes(_ app: Application) throws {
  // route "api/acronyms/search?term=The+string+searched
  app.get("search") { req -> EventLoopFuture<[Acronym]> in
    guard let searchTerm = req.query[String.self, at: "term"] else {
      throw Abort(.badRequest)
    }

    return Acronym.query(on: app.db)
      .group(.or) { group in
        group
          .filter(\.$short == searchTerm)
          .filter(\.$long == searchTerm)
      }
      .all()
  }
}

这行得通。我想把它移到控制器中。所以我在控制器中创建了一个处理函数。

import Vapor
import Fluent

struct AcronymsController: RouteCollection {
  let app: Application

  func boot(routes: RoutesBuilder) throws {
    routes.get("search", use: search)
  }
  
  func search(req: Request) throws -> EventLoopFuture<[Acronym]> {
    guard let searchTerm = req.query[String.self, at: "term"] else {
            throw Abort(.badRequest)
          }

          return Acronym.query(on: app.db)
            .filter(\Acronym.$short == searchTerm)
            .filter(\Acronym.$long == searchTerm)
            .all()
  }
}

但我得到 Swift 编译器错误:Binary operator '==' cannot be applied to operands of type 'KeyPath<Acronym, FieldProperty<Acronym, String>>' and 'String'

为什么 filter 和运算符 == 在控制器中不起作用?

环境

您需要在控制器文件中 import Fluent 以便编译器可以看到运算符重载触发查询