gpt4 book ai didi

android - 房间的 `onDelete = CASCADE` 在迁移期间不工作

转载 作者:行者123 更新时间:2023-12-04 23:59:42 28 4
gpt4 key购买 nike

我有以下表格:

@Entity(
tableName = "users"
)
class Users {
@PrimaryKey(autoGenerate = true)
var id: Long? = null

@NonNull
var name: String? = null
}

@Entity(
tableName = "pets",
foreignKeys = [
ForeignKey(
entity = Users::class,
parentColumns = ["id"],
childColumns = ["owner_id"],
onDelete = ForeignKey.CASCADE
)
]
)
class Pets {
@PrimaryKey(autoGenerate = true)
var id: Long? = null

@NonNull
var name: String? = null

@ColumnInfo(name = "owner_id")
var ownerId: Long? = null
}

当我运行删除所有用户表行的迁移时,宠物表不受影响。行不会自动删除。

object Migration_1_2 : Migration(1, 2) {

override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("""
DELETE FROM users
""")
}
}

即使我在迁移之前执行以下代码 fragment ,它也不起作用。

database.execSQL("PRAGMA foreign_keys=ON;");

我应该怎么做才能使 onDelete = ForeignKey.CASCADE 正常工作?

最佳答案

正如@sergiytikhonov 在他的评论中指出的那样,在迁移函数中启用 foreign_keys 约束没有任何效果。这是因为 migrations are executed as part of a transactionthe pragma is a no-op inside a transaction .

在执行迁移之前,我看不到有任何方法可以控制和启用 foreign_keys。我认为您唯一的选择是在迁移过程中明确删除宠物:

override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("""
DELETE FROM pets WHERE owner_id IN (SELECT id FROM users)
""")

database.execSQL("""
DELETE FROM users
""")
}

关于android - 房间的 `onDelete = CASCADE` 在迁移期间不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62064932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com