Hi!.
I'm having a little problem to save an associated id. I don't know if I'm doing it well. Let me explain what it is happen to me.
-- authors definition
CREATE TABLE authors (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT
);
-- books definition
CREATE TABLE books (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
title TEXT,
category TEXT,
price INTEGER,
discount NUMERIC,
stock INTEGER,
author_id INTEGER NOT NULL,
FOREIGN KEY(author_id) REFERENCES authors(id)
);
type Author struct {
ID int32
Name string
}
type Book struct {
ID int32
Title string
Category string
Price int
Discount bool
Stock int
Author Author `ref:"author_id" fk:"id" autosave:"true"`
AuthorID int32
}
I want to save an Author instance and pass it to a Book instance. I was expecting that the relation would save AuthorID automatically but no. It shows this error:
panic: ForeignKeyConstraintError: rel: inconsistent belongs to ref and fk
const dbPath = "./go-rel-example.db"
func main() {
adapter, err := sqlite3.Open(dbPath)
if err != nil {
panic(err)
}
defer adapter.Close()
repo := rel.New(adapter)
err = Example(context.Background(), repo)
if err != nil {
panic(err)
}
}
func Example(ctx context.Context, repo rel.Repository) error {
return repo.Transaction(ctx, func(ctx context.Context) error {
author := Author{
Name: "Anne Paterson",
}
err := repo.Insert(ctx, &author)
if err != nil {
return err
}
log.Println(author)
book := Book{
Title: "A new story",
Category: "horror",
Price: 10,
Discount: false,
Stock: 2,
Author: author,
}
err = repo.Insert(ctx, &book)
if err != nil {
return err
}
log.Println(book)
log.Println("-----DONE-----")
return nil
})
}
Now my questing here is if this can be done. I don have any problem to pass the id to the association, but I thing would be great to pass the saved instance and rel takes the associated id to save it.