从Vapor 3和MySQL数据库开始,我很难弄清Relations部分。
到目前为止,我已经创建了2个模型:Movie
和Actor
。
Movie
可以有许多Actor
,而Actor
可以有许多Movie
。
Movie
型号:
import Vapor
import FluentMySQL
final class Movie: Codable {
var id: Int?
var name: String
var synopsis: String
var dateReleased: Date
var totalGrossed: Float
init(id: Int? = nil, name: String, synopsis: String, dateReleased: Date, totalGrossed: Float) {
self.id = id
self.name = name
self.synopsis = synopsis
self.dateReleased = dateReleased
self.totalGrossed = totalGrossed
}
}
extension Movie {
var actors: Siblings<Movie, Actor, MovieActor> {
return siblings()
}
}
extension Movie: Content {}
extension Movie: Parameter {}
extension Movie: MySQLModel {}
extension Movie: MySQLMigration {
static func prepare(on conn: MySQLConnection) -> Future<Void> {
return MySQLDatabase.create(self, on: conn) { builder in
builder.field(for: \.id, isIdentifier: true)
builder.field(for: \.name)
builder.field(for: \.synopsis)
builder.field(for: \.dateReleased, type: .date)
builder.field(for: \.totalGrossed, type: .float)
}
}
}
Actor
型号:
import Vapor
import FluentMySQL
final class Actor: Codable {
var id: Int?
var firstName: String
var lastName: String
var fullName: String {
return firstName + " " + lastName
}
var dateOfBirth: Date
var story: String
init(id: Int? = nil, firstName: String, lastName: String, dateOfBirth: Date, story: String) {
self.id = id
self.firstName = firstName
self.lastName = lastName
self.dateOfBirth = dateOfBirth
self.story = story
}
}
extension Actor {
var actors: Siblings<Actor, Movie, MovieActor> {
return siblings()
}
}
extension Actor: Content {}
extension Actor: Parameter {}
extension Actor: MySQLModel {}
extension Actor: MySQLMigration {
static func prepare(on conn: MySQLConnection) -> Future<Void> {
return MySQLDatabase.create(self, on: conn) { builder in
builder.field(for: \.id, isIdentifier: true)
builder.field(for: \.firstName)
builder.field(for: \.lastName)
builder.field(for: \.dateOfBirth, type: .date)
builder.field(for: \.story, type: .text)
}
}
}
我还为关系建立了MovieActor
模型作为MySQLPivot
:
import Vapor
import FluentMySQL
final class MovieActor: MySQLPivot {
typealias Left = Movie
typealias Right = Actor
static var leftIDKey: LeftIDKey = \.movieID
static var rightIDKey: RightIDKey = \.actorID
var id: Int?
var movieID: Int
var actorID: Int
init(movieID: Int, actorID: Int) {
self.movieID = movieID
self.actorID = actorID
}
}
extension MovieActor: MySQLMigration {}
并将它们添加到configure.swift文件的“迁移”部分:
var migrations = MigrationConfig()
migrations.add(model: Movie.self, database: .mysql)
migrations.add(model: Actor.self, database: .mysql)
migrations.add(model: MovieActor.self, database: .mysql)
services.register(migrations)
可以很好地创建数据库中的所有表,但是在调用get all movies
服务时我没有收到这种关系。我刚刚收到Movie
的属性:
final class MoviesController {
func all(request: Request) throws -> Future<[Movie]> {
return Movie.query(on: request).all()
}
}
[
{
"id": 1,
"dateReleased": "2017-11-20T00:00:00Z",
"totalGrossed": 0,
"name": "Star Wars: The Last Jedi",
"synopsis": "Someone with a lightsaber kills another person with a lightsaber"
},
{
"id": 3,
"dateReleased": "1970-07-20T00:00:00Z",
"totalGrossed": 0,
"name": "Star Wars: A New Hope",
"synopsis": "Someone new has been discovered by the force and he will kill the dark side with his awesome lightsaber and talking skills."
},
{
"id": 4,
"dateReleased": "2005-12-20T00:00:00Z",
"totalGrossed": 100000000,
"name": "Star Wars: Revenge of the Sith",
"synopsis": "Anakin Skywalker being sliced by Obi-Wan Kenobi in an epic dual of fates"
}
]
您的帮助将不胜感激!非常感谢:)
答案 0 :(得分:11)
因此,我相信您期望这种关系将反映在查询Movie模型时返回的内容中。因此,例如,您希望为电影返回这样的内容:
{
"id": 1,
"dateReleased": "2017-11-20T00:00:00Z",
"totalGrossed": 0,
"name": "Star Wars: The Last Jedi",
"synopsis": "Someone with a lightsaber kills another person with a lightsaber",
"actors": [
"id": 1,
"firstName": "Leonardo",
"lastName": "DiCaprio",
"dateOfBirth": "1974-11-11T00:00:00Z",
"story": "Couldn't get an Oscar until wrestling a bear for the big screen."
]
}
但是,将Movie和Actor模型作为同级连接只是为您提供了从电影中查询actor的便利,就好像actor是Movie模型的属性一样。
movie.actors.query(on: request).all()
上面的那一行返回:Future <[Actor]>
从Actor对象访问电影时反之亦然:
actor.movies.query(on: request).all()
上面的那一行返回:Future <[电影]>
如果您希望它以相同的响应返回影片及其演员,就像我想像的那样,那么我认为最好的方法是创建一个Content响应结构,如下所示:
struct MovieResponse: Content {
let movie: Movie
let actors: [Actor]
}
您的“全部”功能现在看起来像这样:
func all(_ request: Request) throws -> Future<[MovieResponse]> {
return Movie.query(on: request).all().flatMap { movies in
let movieResponseFutures = try movies.map { movie in
try movie.actors.query(on: request).all().map { actors in
return MovieResponse(movie: movie, actors: actors)
}
}
return movieResponseFutures.flatten(on: request)
}
}
此函数查询所有电影,然后迭代每个电影,然后使用“演员”同级关系来查询该电影的演员。此演员查询会为其查询演员的每部电影返回Future <[Actor]>。映射从那个关系返回的内容,以便您可以以[Actor]而不是Future <[Actor]>的身份访问actor,然后将与电影结合起来的内容作为MovieResponse返回。
此movieResponseFutures实际组成的是一组MovieResponse期货: [未来<[MovieResponse]>]
要将该期货数组转换为由数组组成的单个期货,请使用flatten(on :)。这等待等待每个单独的期货完成,然后将它们全部作为一个期货返回。
如果您真的想在电影对象json中使用Actor的数组,则可以像下面这样构造MovieResponse结构:
struct MovieResponse: Content {
let id: Int?
let name: String
let synopsis: String
let dateReleased: Date
let totalGrossed: Float
let actors: [Actor]
init(movie: Movie, actors: [Actor]) {
self.id = movie.id
self.name = movie.name
self.synopsis = movie.synopsis
self.dateReleased = movie.dateReleased
self.totalGrossed = movie.totalGrossed
self.actors = actors
}
}
答案 1 :(得分:1)
因此,潜在的问题是Codable
响应中未提供计算的属性。您需要做的是定义一个新类型MoviesWithActors
并将其填充并返回。或者提供第二个终结点,例如/movies/1/actors/
,它可以获取特定电影的所有演员。 REST更适合,但这取决于您的用例,因为您可能不希望额外的请求等