agrosner / DBFlow

A blazing fast, powerful, and very simple ORM android database library that writes database code for you.
MIT License
4.87k stars 598 forks source link

How to load list of objects with related objects (annotated with ForeignKey)? #1725

Open milovan92 opened 3 years ago

milovan92 commented 3 years ago

DBFlow Version: 4.2.4

Bug or Feature Request: /

Description:

How to load list of objects with related objects (annotated with ForeignKey)?

Code example:

@Table(database = Database::class)
class A : BaseModel() {
    @Column @PrimaryKey var id: Int = 0
    @Column var name = ""
    @Column @ForeignKey(onDelete = ForeignKeyAction.RESTRICT, saveForeignKeyModel = true)
    var b: B? = null
}
@Table(database = Database::class)
class B : BaseModel() {
    @Column @PrimaryKey var id: Int = 0
    @Column var name = ""
}

I need to load list of A objects populated with B object. When I load 100 objects of class A and then iterate on them one by one and access B through them, DBFlow fires 100 SELECT queries. I wish to somehow load B's together with A's in a single query, and then populate A's with B's so no further queries are fired. So I was expecting that if query has INNER JOIN that it will automatically populate A object with B objects. Executed query:

SELECT DISTINCT `a`.`id`,`a`.`name`,`b`.`id`,`b`.`name` FROM `A` AS `a` INNER JOIN `B` AS `b` ON `a`.`b_id`=`b`.`id`