兄弟姐妹在Vapor中相同模型之间的关系

问题描述 投票:2回答:2

我有一个User模型,我想添加一个friends属性。朋友,应该是其他Users。

我创建了UserFriendsPivot

final class UserFriendsPivot: MySQLPivot, ModifiablePivot {
    var id: Int?
    var userID: User.ID
    var friendID: User.ID

    typealias Left = User
    typealias Right = User

    static var leftIDKey: WritableKeyPath<UserFriendsPivot, Int> {
        return \.userID
    }

    static var rightIDKey: WritableKeyPath<UserFriendsPivot, Int> {
        return \.friendID
    }

    init(_ user: User, _ friend: User) throws {
        self.userID   = try user  .requireID()
        self.friendID = try friend.requireID()
    }
}

extension UserFriendsPivot: Migration {
    public static var entity: String {
        return "user_friends"
    }
}

我将friends属性添加到User

var friends: Siblings<User, User, UserFriendsPivot> {
    return siblings()
}

现在,我在return siblings()的行上看到以下错误:

模仿使用'兄弟姐妹(相关:通过:)'

我试着用以下代替它:

return siblings(related: User.self, through: UserFriendsPivot.self)

......没有运气。

我知道这两个代码片段应该可以工作,因为我直接从我在EventUser之间构建的另一个兄弟姐妹关系中复制它们,这种关系工作得很好。 我看到的唯一区别是我正在尝试在相同模型之间建立关系。

我能做什么?

swift relationship vapor
2个回答
1
投票

尝试用以下内容替换你的friends定义:

var friends: Siblings<User,UserFriendsPivot.Right, UserFriendsPivot> {
    return User.siblings()
}

编辑:

它应该与LeftRight一起作为同一个表,但似乎失败,因为别名解析为基值。即Xcode中的自动完成功能显示siblings的所有候选者最终都是类型:

Siblings<User, User, UserFriendsPivot> siblings(...)

代替:

Siblings<User, UserFriendsPivot.Right, UserFriendsPivot> siblings(...)

和类似的。

我建议在GitHub上提出一个bug。与此同时,如何创建一个具有不同名称和设置的User副本:

static let entity = "User"

使用相同的物理表。不漂亮,但它可能让你工作。


1
投票

这里的问题是,在同一个ModelUser-User)兄弟姐妹的关系中,Fluent无法推断出你指的是哪个兄弟姐妹 - 需要指明哪一方。

extension User {
    // friends of this user
    var friends: Siblings<User, User, UserFriendsPivot> {
        return siblings(UserFriendsPivot.leftIDKey, UserFriendsPivot.rightIDKey)
    }

    // users who are friends with this user
    var friendOf: Siblings<User, User, UserFriendsPivot> {
        return siblings(UserFriendsPivot.rightIDKey, UserFriendsPivot.leftIDKey)
    }
}

另一个相同的Model后果是您将无法使用附加便捷方法添加到数据透视表,并需要手动创建:

let pivot = try UserFriendsPivot(user, friend)
pivot.save(on: req)

(还有其他方法可以解决这个问题,我只是发现这些直接方法最容易使用。指定边和反转关键位置以获得反比关系是重要的概念。)


正如grundoon所回答的那样

© www.soinside.com 2019 - 2024. All rights reserved.