GORM Playground Link
https://github.com/go-gorm/playground/pull/630
Description
I find that many2many does not support Non-PrimaryKey.
Reproduce steps:
GORM_DIALECT=postgres go test -v
CREATE TABLE "stu_compannys" ("companny_name" text,"stuname" text,PRIMARY KEY ("companny_name","stuname"),CONSTRAINT "fk_stu_compannys_companny" FOREIGN KEY ("companny_name") REFERENCES "compannies"("name"),CONSTRAINT "fk_stu_compannys_stu" FOREIGN KEY ("stuname") REFERENCES "stus"("stuname"))
main_test.go:28 ERROR: column "stu_id" of relation "stu_compannys" does not exist (SQLSTATE 42703)
Comment From: twocs
The description of the problem doesn't match the code. The problem in the code is that the Companny table has a many2many relationship with the Stu table, and then Stu table has a separate many2many relationship with the Companny table.
However, the many2many relationship was only defined halfway, on the Companny slice Stus []Stu.
But on the Stu slice []Companny there was only gorm:"many2many" without details of how Gorm should go about joining the Stu's Compannies slice with the other table.
Just update the code to:
type Companny struct {
ID int `gorm:"primarykey"`
Name string `gorm:"index:,unique"`
Stus []Stu `gorm:"many2many:stu_compannys;foreignKey:Name;joinForeignKey:CompannyName;References:Stuname;joinReferences:Stuname;"`
}
type Stu struct {
ID int `gorm:"primarykey"`
Stuname string `gorm:"index:,unique"`
Compannies []Companny `gorm:"many2many:stu_compannys;foreignKey:Stuname;joinForeignKey:Stuname;References:Name;joinReferences:CompannyName;"`
}
Also the assertion should be updated to access the Error, and then it passes:
if err.Error!=nil{
t.Fatal(err.Error)
}