pg
pg copied to clipboard
foreign key to non pk but with unique and not null constraints.
type Answers struct {
TestResultsId string `pg:",pk,type:uuid" json:"test_results_id"`
TestResults *TestResults `json:"test_results,omitempty"`
QuestionId string `json:"question_id" pg:"type:uuid,pk"`
Question *Question `json:"question"`
}
type TestResults struct {
Id string `json:"id" pg:",unique,notnull,type:uuid,default:uuid_generate_v4(),nopk"`
TestId string `json:"test_id" pg:"type:uuid,on_delete:CASCADE,pk"`
Test *Test `json:"test,omitempty"`
StudentId string `json:"student_id" pg:"type:uuid,on_delete:CASCADE,pk"`
Student *Student `json:"student,omitempty"`
}
This doesn't seem to create foreign key on TestResults field of struct Answers , instead I see a jsonb type test_results column in db. I tried using fk:"test_results_id" tag on TestResults field. Edit: Removing nopk and pk tags from TestResults that is essentially making ID as pk solves it.
I think supporting this will be difficult if you support the non-pk referencing fks. If this is true then I would definitely prefer the multi pk feature (the already implemented one) over the non-pk thing.
What queries and indexes are you planning on using that makes that primary key more efficient that the absolute unique row identifier should not be the primary key, but instead just a unique constraint?
I want to make answers a weak entity with partial key pointing to test_results. so that I can call db.Model(&TestResults{}).Relation("Answers")
and let go-pg do the heavy lifting.
Ideally I would do that by defining a fk constraint on Answers table - foreign key (studentId,TestId) referencing TestResults(StudentId,TestId)
but I couldn't find a way through tags so introduced a new uuid field which will be unique for sure anyways and referenced it.