Sqlite.swift: create subUser table error: unknown column "user_id" in foreign key definition (code: 1)

Created on 22 Sep 2017  路  1Comment  路  Source: stephencelis/SQLite.swift

My code looks like this :

static let shared = CYDatabaseManager()

private init() {
    let sqlFilePath = NSHomeDirectory() + "/Documents" + "/db.sqlite3"
    do {
        db = try Connection(sqlFilePath)
    } catch {
        print("connect db error: \(error)")
    }
    createdTableUser()
    createdTableSubUser()
}

func createdTableUser()  {
        do {
            try db.run(users.create(ifNotExists: true) { t in
                    t.column(id, primaryKey: true)
                    t.column(password)
                    t.column(email, unique: true)
                })
        } catch { print("create user table error: \(error)") }
    }

    func createdTableSubUser()  {
        do {
            let des = try db.run(subUsers.create(ifNotExists: true) { t in
                t.column(sid, primaryKey: true)
                t.column(name, unique: true)
                t.column(createTime)
                t.column(sex)
                t.column(age)
                t.column(height)
                t.column(weight)
                t.column(highBP)
                t.column(lowBP)
                t.foreignKey(user_id, references: users, id)
            }).description
            print(des)
        } catch { print("create subUser table error: \(error) \nEnd") }
        db.trace({ (statement) in
            print("---\(statement)")
        })
    }

The Xcode print create subUser table error: unknown column "user_id" in foreign key definition (code: 1) ,and the method trace nothing was returned.

Thanks!!! I have no idea, give me a chance.

question

Most helpful comment

You need to create the column first:

t.column(user_id)
t.foreignKey(user_id, references: users, id)

>All comments

You need to create the column first:

t.column(user_id)
t.foreignKey(user_id, references: users, id)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

zackdh9 picture zackdh9  路  5Comments

Viswanth92 picture Viswanth92  路  3Comments

leminhtuan2015 picture leminhtuan2015  路  5Comments

Tchoupinax picture Tchoupinax  路  8Comments

bitflying picture bitflying  路  5Comments