我想问你一些建议,如何在两个表上使用 LEFT JOIN
后访问对象 . 我've got tables defined in external file File.db and I'm将它加载到Android上的Room数据库 . 我已经定义了两个表:
CREATE TABLE Example (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`description` TEXT,
`source_url` TEXT
);
CREATE TABLE Example_dates (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`example_id` INTEGER NOT NULL,
`color` INTEGER NOT NULL,
`date_from` TEXT,
`date_to` TEXT,
FOREIGN KEY(`example_id`) REFERENCES `Example`(`id`)
);
我的实体是:
@Entity(
tableName = "Example"
)
data class Example constructor(
@PrimaryKey @ColumnInfo(name = "id") var id: Int,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String?,
@ColumnInfo(name = "source_url") var sourceUrl: String?
)
@Entity(
tableName = "Example_dates",
foreignKeys = arrayOf(
ForeignKey(entity = Example::class, parentColumns = ["id"],
childColumns = ["example_id"]))
)
data class Example_dates constructor(
@PrimaryKey @ColumnInfo(name = "id") var id: Int,
@ColumnInfo(name = "example_id") var exampleId: Int,
@ColumnInfo(name = "color") var color: Int,
@ColumnInfo(name = "date_from") var dateFrom: String?,
@ColumnInfo(name = "date_to") var dateTo: String?
)
道对象:
@Dao
interface AnimalDao {
@Query(
"SELECT * FROM example_dates LEFT JOIN example ON example_dates.example_id = example.id")
fun loadAll(): Cursor
}
而我正在构建这样的DB:
RoomAsset
.databaseBuilder(context, AppDatabase::class.java, "File.db")
.build()
有没有办法,如何以不同的方式从SQL语句中获取合并数据然后是Cursor?我试图用 @Ignore
注释的 data class Example
构造函数添加更多字段但是我得到了表中差异的错误 - "Expected/Found" . 或者是基于游标的解决方案正确的实施方式?
谢谢 .
1 回答
好的,正如官方文件所述https://developer.android.com/training/data-storage/room/accessing-data
所以我试图用我需要的所有字段创建另一个
data class named ExampleDetail
,在DAO
对象中我正在返回List而不是Cursor .谢谢 .