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

Getting children from parent returning empty list on OneToMany #952

Closed ricardomello closed 8 years ago

ricardomello commented 8 years ago

DBFlow Version: 3.1.1 Issue Kind: Question

Description:

Hi, I'm trying to make one to many relations work on DBFlow. I have a model Project that can have many Reports. The models are:

@ModelContainer
@Table(database = AppDatabase.class)
public class Project extends BaseModel {
    @Expose
    @Column
    @PrimaryKey
    @Unique(onUniqueConflict = ConflictAction.REPLACE)
    @SerializedName("id")
    public String id;

    (...)

    List<Report> reports;

    @OneToMany(methods = {OneToMany.Method.SAVE, OneToMany.Method.DELETE}, variableName = "reports")
    public List<Report> getReports() {
        if (reports == null || reports.isEmpty()) {
            reports = SQLite.select().from(Report.class).where(Report_Table.parent_id.eq(id)).queryList();
        }

        return reports;
    }
}
@ModelContainer
@Table(database = AppDatabase.class)
public class Report extends BaseModel {
    @Expose
    @Column
    @PrimaryKey
    @Unique(onUniqueConflict = ConflictAction.REPLACE)
    @SerializedName("id")
    public String id;

    (...)

    @ForeignKey
    ForeignKeyContainer<Project> parent;

    public void associateParent(Project project) {
        this.parent = FlowManager.getContainerAdapter(Project.class).toForeignKeyContainer(project);
    }
}

And this is how I make the association:

FlowManager.getDatabase(PunchDatabase.class).executeTransaction(databaseWrapper -> {
    Report r = report;
    r.associateParent(project);
    r.save(databaseWrapper);
});

I've tried different options with ConflictAction and OneToMany.Method but that didn't change anything. I also followed the documentation and read a lot of issues here trying to solve this but so far I had no success. Is there anything else needed to make this work?

Thanks.

agrosner commented 8 years ago

by default the @ForeignKey do no save to the DB when saving the child object. I think the issue can be fixed by:

@ForeignKey(saveForeignKeyModel = true)
    ForeignKeyContainer<Project> parent;