如何使用Data Model在sqlite.swift中创建外键

时间:2016-07-27 12:10:02

标签: ios database sqlite swift2

我正在使用sqlite.swift进行数据库创建。我已经借助此链接http://masteringswift.blogspot.in/2015/09/create-data-access-layer-with.html创建了一个类。我想在播放器表引用中的teamID(列)上创建一个外键作为团队表teamID(列)。

这是团队和玩家表的助手类:

class TeamDataHelper: DataHelperProtocol {
static let TABLE_NAME = "Teams"

static let table = Table(TABLE_NAME)
static let teamId = Expression<Int64>("teamid")
static let city = Expression<String>("city")
static let nickName = Expression<String>("nickname")
static let abbreviation = Expression<String>("abbreviation")


typealias T = Team

static func createTable() throws {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    do {
        let _ = try DB.run( table.create(ifNotExists: true) {t in
            t.column(teamId, primaryKey: true)
            t.column(city)
            t.column(nickName)
            t.column(abbreviation)
            })

    } catch _ {
        // Error throw if table already exists
    }

}

static func insert(item: T) throws -> Int64 {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    if (item.city != nil && item.nickName != nil && item.abbreviation != nil) {
        let insert = table.insert(city <- item.city!, nickName <- item.nickName!, abbreviation <- item.abbreviation!)
        do {
            let rowId = try DB.run(insert)
            guard rowId > 0 else {
                throw DataAccessError.Insert_Error
            }
            return rowId
        } catch _ {
            throw DataAccessError.Insert_Error
        }
    }
    throw DataAccessError.Nil_In_Data

}

static func delete (item: T) throws -> Void {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    if let id = item.teamId {
        let query = table.filter(teamId == id)
        do {
            let tmp = try DB.run(query.delete())
            guard tmp == 1 else {
                throw DataAccessError.Delete_Error
            }
        } catch _ {
            throw DataAccessError.Delete_Error
        }
    }
}

static func find(id: Int64) throws -> T? {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    let query = table.filter(teamId == id)
    let items = try DB.prepare(query)
    for item in  items {
        return Team(teamId: item[teamId] , city: item[city], nickName: item[nickName], abbreviation: item[abbreviation])
    }

    return nil

}

static func findAll() throws -> [T]? {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    var retArray = [T]()
    let items = try DB.prepare(table)
    for item in items {
        retArray.append(Team(teamId: item[teamId], city: item[city], nickName: item[nickName], abbreviation: item[abbreviation]))
    }

    return retArray

}
}



class PlayerDataHelper: DataHelperProtocol {
static let TABLE_NAME = "Players"

static let playerId = Expression<Int64>("playerid")
static let firstName = Expression<String>("firstName")
static let lastName = Expression<String>("lastName")
static let number = Expression<Int>("number")
static let teamId = Expression<Int64>("teamid")
static let position = Expression<String>("position")


static let table = Table(TABLE_NAME)

typealias T = Player

static func createTable() throws {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    do {
        _ = try DB.run( table.create(ifNotExists: true) {t in

            t.column(playerId, primaryKey: true)
            t.column(firstName)
            t.column(lastName)
            t.column(number)
            t.column(teamId)
            t.column(position)


            })
    } catch _ {
        // Error thrown when table exists
    }
}

static func insert(item: T) throws -> Int64 {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    if (item.firstName != nil && item.lastName != nil && item.teamId != nil && item.position != nil) {
        let insert = table.insert(firstName <- item.firstName!, number <- item.number!, lastName <- item.lastName!, teamId <- item.teamId!, position <- item.position!.rawValue)
        do {
            let rowId = try DB.run(insert)
            guard rowId >= 0 else {
                throw DataAccessError.Insert_Error
            }
            return rowId
        } catch _ {
            throw DataAccessError.Insert_Error
        }
    }
    throw DataAccessError.Nil_In_Data
}

static func delete (item: T) throws -> Void {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    if let id = item.playerId {
        let query = table.filter(playerId == id)
        do {
            let tmp = try DB.run(query.delete())
            guard tmp == 1 else {
                throw DataAccessError.Delete_Error
            }
        } catch _ {
            throw DataAccessError.Delete_Error
        }
    }

}

static func find(id: Int64) throws -> T? {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    let query = table.filter(playerId == id)
    let items = try DB.prepare(query)
    for item in  items {
        return Player(playerId: item[playerId], firstName: item[firstName], lastName: item[lastName], number: item[number], teamId: item[teamId], position: Positions(rawValue: item[position]))
    }

    return nil

}

static func findAll() throws -> [T]? {
    guard let DB = SQLiteDataStore.sharedInstance.BBDB else {
        throw DataAccessError.Datastore_Connection_Error
    }
    var retArray = [T]()
    let items = try DB.prepare(table)
    for item in items {
        retArray.append(Player(playerId: item[playerId], firstName: item[firstName], lastName: item[lastName], number: item[number], teamId: item[teamId], position: Positions(rawValue: item[position])))
    }

    return retArray
}
}

在上面的播放器表中,我想为teamID创建外键作为参考团队表teamID。如果我正在创建“t.foreignKey(teamID,on:TeamDataHelper.teamID)”之类的外键,那么它就会出错。

任何人都可以向我提出任何帮助。

1 个答案:

答案 0 :(得分:0)

1.检查你的陈述。对于Swift 4(和Xcode 9),它应该是:

t.foreignKey(teamId, references: teamTable, teamId, delete: .setNull)
// FOREIGN KEY("teamid") REFERENCES "Team"("teamid") ON DELETE SET NULL

将它放在PlayerDataHelper类的createTable()函数中的DB.run中

2.您还需要在PlayerDataHelper类中使用以下代码

teamTable = Table("Team")

参考:SQLite.swift ~> 0.11.4 GitHub Documentation