pg icon indicating copy to clipboard operation
pg copied to clipboard

foreign key to non pk but with unique and not null constraints.

Open MohitKS5 opened this issue 4 years ago • 3 comments

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.

MohitKS5 avatar Jan 23 '20 04:01 MohitKS5

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.

MohitKS5 avatar Jan 23 '20 05:01 MohitKS5

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?

elliotcourant avatar Jan 25 '20 16:01 elliotcourant

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.

MohitKS5 avatar Jan 26 '20 07:01 MohitKS5