0

我想添加一个路由来通过搜索特定的字符串来获取匹配的数据。我将路线添加到routes(_:)routes.swift

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'.

为什么filterwith operator==在控制器中不起作用?

环境

  • 蒸汽 4.27.1(工具箱 18.2.1)
  • 斯威夫特 5.2.4
  • macOS Catalina 10.15.6
4

1 回答 1

1

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

于 2020-08-05T22:58:29.147 回答