From 8545f588249455f922d415a699e0526c779a1639 Mon Sep 17 00:00:00 2001 From: Yan-Fa Li Date: Thu, 2 Jul 2015 11:03:54 -0700 Subject: [PATCH] No auto_inc of gorm:"primary_key" if foreignkey If you are trying to create a table to store metadata about the relationship of two entities, e.g. Product and Store and the quantity of product available at that store. You may wish to use a composite foreign key relationship. If you also wish to use gorm to generate the SQL to create the schema, but default gorm will add the auto_increment keyword to tables which are both primary and integer. This is a undesirable for composite foreign key relationships and generates invalid sql statements. If you have a struct field which is a primary key and is marked as a foreign key, disable the auto increment behavior while generating the schema. --- README.md | 15 +++++++++++++++ model_struct.go | 4 ++++ 2 files changed, 19 insertions(+) diff --git a/README.md b/README.md index ccab06db..b8b23416 100644 --- a/README.md +++ b/README.md @@ -1116,6 +1116,21 @@ type Product struct { } ``` +## Composite Foreign Primary Integer Keys + +```go +type ProductStore struct { + ProductID int64 `gorm:"primary_key;foreignkey"` + StoreID int64 `gorm:"primary_key;foreignkey"` + Quantity int +} +``` + +When you declare a gorm primary key as foreign, there is likely no good use case for also auto incrementing the field. +This disables the auto increment behavior when creating the table from gorm. + + + ## Database Indexes & Foreign Key ```go diff --git a/model_struct.go b/model_struct.go index 10423ae2..676bdbde 100644 --- a/model_struct.go +++ b/model_struct.go @@ -350,6 +350,10 @@ func (scope *Scope) generateSqlTag(field *StructField) string { autoIncrease = true } + if field.IsPrimaryKey && field.IsForeignKey { + autoIncrease = false + } + sqlType = scope.Dialect().SqlTag(reflectValue, size, autoIncrease) }