使用fluent的vapor 3中的多对多关系

lnvxswe2  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(307)

我想知道如何使用fluent和fluentmysql在vapor3中创建多对多关系,如vapor2文档中所述
遗憾的是,Vapor3的文档还没有更新,而 Pivot 协议已更改。
我想做的是:我有两门课, User 以及 Community . 一 Communitymembers 以及 User 可以是多个 Community s。
目前,我的代码如下所示:

import Vapor
import FluentMySQL

final class Community: MySQLModel {
    var id: Int?
    //Community Attributes here
}

final class User: MySQLModel {
    var id: Int?
    //User Attributes here
}

extension Community {
    var members: Siblings<Community, User, Pivot<Community, User>> {
        return siblings()
    }
}

但是,这会导致以下编译器错误: Cannot specialize non-generic type 'Pivot' 以及 Using 'Pivot' as a concrete type conforming to protocol 'Pivot' is not supported .
我看到有一个协议扩展名为 ModifiablePivot 但我不知道如何使用它,因为没有任何文档或示例代码。
感谢您的帮助。提前谢谢!

btxsgosb

btxsgosb1#

我有同样的问题,这两个答案对我来说都不够,所以我只是张贴我的解决方案,这对我是有效的。

// in CommunityUser.swift
import Vapor
import FluentMySQL

final class CommunityUser: MySQLPivot {

    typealias Left = User
    typealias Right = Community

    static var leftIDKey: LeftIDKey = \.userID
    static var rightIDKey: RightIDKey = \.communityID

    var id: Int?
    var userID: Int
    var communityID: Int

    init(id: Int?, userID: Int, communityID: Int) {
        self.id = id
        self.userID = userID
        self.communityID = communityID
    }

}

// CommunityUser didn't conform to MySQLMigration
// This simple line solves the problem
extension CommunityUser: MySQLMigration { }

为了我 CommunityUser 也需要在数据库中迁移。

// in configure.swift
migrations.add(model: CommunityUser.self, database: .mysql)
2ekbmq32

2ekbmq322#

fluent3不再提供像 Pivot 流利2。您应该做的是创建一个符合 Pivot . 中有一些助手类型 FluentMySQL 为了这个。

final class CommunityUser: MySQLPivot {
    // implement the rest of the protocol requirements
    var communityID: Community.ID
    var userID: User.ID
}

然后使用 CommunityUser 代替 Pivot<Community, User> .

wpcxdonn

wpcxdonn3#

完整代码:

import Vapor
import FluentSQLite

final class Community: SQLiteModel {
    var id: Int?
    //Community Attributes here
}

final class User: SQLiteModel {
    var id: Int?
    //User Attributes here
}

extension Community {
    var members: Siblings<Community, User, CommunityUser> {
        return siblings()
    }
}

final class CommunityUser: SQLitePivot {
    typealias Left = User
    typealias Right = Community
    static let leftIDKey: LeftIDKey = \.userID
    static let rightIDKey: RightIDKey = \.communityID
    var id: Int?
    var userID: Int
    var communityID: Int
}

相关问题