Question about foreign key constraints

from the CommonsWare Community archives

At August 7, 2019, 3:07pm, ronnie173 asked:

I am getting a foreign key exception when i try to insert into a table that has the foreign key constraint. I am not understanding why I am getting an error. So i think that the error is there because the table is empty. So my question is when you try to insert into say the parent table does the child table have to already have data? I also tried to add this into Android Development but couldn’t


At August 7, 2019, 3:24pm, mmurphy replied:

Usually not. Usually in a 1:N relation, the child has a column that points to the parent table. So inserting a row in the child requires that the parent row already exist. The parent usually does not have a column that points to the child, so there is no requirement for the child table to have any particular data before you insert data into the parent.


At August 7, 2019, 3:30pm, ronnie173 replied:

Ok the parent is the table with the foreign key right? Like in the below isn’t the Customer class the parent?

foreignKeys = [
ForeignKey(
entity = Receipt::class,
parentColumns = [“id”],
childColumns = [“receipt_id”])
],
indices = [Index(value = [“receipt_id”], unique = true)])
class Customer


At August 7, 2019, 4:28pm, mmurphy replied:

In a 1:N relation, usually the “1” side is what is called the parent.

I do not have your entire Customer or Receipt class definitions, including their columns. Your Customer has a receipt_id, which seems strange to me. The implication is that a Receipt has multiple Customer objects (1:N with Receipt as the parent). Even if you do have the notion of splitting a receipt among multiple people, I would think that is better modeled as an M:N relationship, as a person usually has multiple receipts over time.

But, again, I am not in charge of your data model, and so I may be misinterpreting your code snippet.