我有以下表格:
@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
}
当我运行删除所有用户表行的迁移时,pets 表不受影响。这些行不会自动删除。
object Migration_1_2 : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("""
DELETE FROM users
""")
}
}
即使我在迁移之前执行以下代码片段,它也不起作用。
database.execSQL("PRAGMA foreign_keys=ON;");
我应该做什么才能使onDelete = ForeignKey.CASCADE
work?
正如@sergiytikhonov 在他的评论中指出的那样,在迁移函数中启用foreign_keys 约束没有任何效果。这是因为迁移作为事务的一部分执行 https://developer.android.com/reference/androidx/room/migration/Migration#migrate(androidx.sqlite.db.SupportSQLiteDatabase) and pragma 是事务内的无操作 https://www.sqlite.org/pragma.html#:~:text=PRAGMA%20foreign_keys%20%3D%20boolean%3B,no%20pending%20BEGIN%20or%20SAVEPOINT..
我没有看到任何方法来获得控制和启用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
""")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)