Skip to content
Advertisement

Flutter Insert data into the database sqflite

I need to insert the data one at a time and add it to the end of the string, but what happens is that the way I’m doing is overwriting the data

 for (var i = 0; i< isChecked.length; i++) {
  receipt.ingredientsReceipt = isChecked[i]; //receipt is table name, ingredientsReceipt is column name
  print(isChecked[i]);// isChecked is my list containing [ING 1, ING 2, ING 3]
 }

Output:

I/flutter ( 5360): ING 1
I/flutter ( 5360): ING 2
I/flutter ( 5360): ING 3

This is my SQL:

CREATE TABLE receipt(id INTEGER PRIMARY KEY AUTOINCREMENT, nameReceipt TEXT, descReceipt TEXT, ingredientsReceipt TEXT)

Output SQL:

{id: null, nameReceipt: TEST, descReceipt: TEST, ingredientsReceipt: ING 3}

I need it to be like this:

{id: 1, nameReceipt: TEST, descReceipt: TEST, ingredientsReceipt: ING 1, ING 2, ING 3}

Advertisement

Answer

According to my comment, use 3 tables :

RECEIPTS

id nameReceipt descReceipt
1 name1 desc1
2 name2 desc2

INGREDIENTS

id name
1 ingr1
2 ingr2
3 ingr3
4 ingr4

RECEIPT_INGREDIENT

id receipt_fk ingredient_fk
1 1 1
2 1 2
3 1 3
4 2 3
5 2 4

So when you want to get a receipt, you’ll have to write a query to select data from receipt, join with receipt_ingredient (where receipt.id = receipt_ingredient.receipt_fk), join with ingredient (where receipt_ingredient.ingredeint_fk = ingredient.id).

Ex. get receipt id = 1 =>

id nameReceipt descReceipt receipt_fk ingredient_fk name
1 name1 desc1 1 1 ingr1
1 name1 desc1 1 2 ingr2
1 name1 desc1 1 3 ingr3
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement