我正在使用Vapor编写服务器端Swift,使用Fluent访问Postgres数据库。它运行得很好,但是我有几个关于枢轴的问题。
我有一个饲料模型和一个商品模型。Feed包含许多文章,一篇文章可以出现在许多提要中。这是由Fluent定义的兄弟关系,我有一个Pivot,它可以很好地将文章添加到提要中。但是,目前可以多次将同一篇文章添加到相同的Feed中,因为Feed_Article数据透视表的主键是它自己的唯一id字段。
我有两个问题:
- Do I need to get the Feed's sibling Articles and go through them to see if the Article's id is already in there? Seems a little painful.
- Ie. How can I remove an Article from a Feed?
- At the moment the only way I can do it is by writing the raw SQL to delete from Feed\_Article, but that seems wrong.
我使用的是VaporPostgreSQL驱动程序,所以我不确定所有的Fluent实现都是可用的(例如。我不能使用UUID I,因为它们还不是这个驱动程序的一部分。)
谢谢大家
-TJ
补充:
我最终创建了一个Pivot扩展。这是可行的,但感觉应该有一个更好的方法来做到这一点。不管怎么说,分享是为了防止它帮助别人。
extension Pivot {
static func remove(leftId: Node?, rightId: Node?) throws {
/// Get the database driver
guard let db = drop.database?.driver as? PostgreSQLDriver else {
Logger.error("Failed to get database")
return
}
/// Check that we have valid id's
guard let leftId = leftId?.int, let rightId = rightId?.int else {
Logger.error("Invalid id's")
return
}
/// Delete the rows
let sql = "DELETE FROM \(name) WHERE \(left.name)_\(left.idKey) = \(leftId) AND \(right.name)_\(right.idKey) = \(rightId)"
Logger.debug("SQL: \(sql)")
try db.raw(sql)
}
}发布于 2017-03-28 13:47:00
您应该能够查询,删除等枢轴像任何其他流畅的对象。
例如:
try Pivot<User, Pet>.query().fiter("user_id", x).delete()在Fluent 2 (2.0.0-beta.1,在撰写本文时)中,有方便方法在Siblings关系上这样做。
例如:
try user.pets.add(newPet)https://stackoverflow.com/questions/42994912
复制相似问题