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.
This commit is contained in:
parent
27a442b5ec
commit
8545f58824
15
README.md
15
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
|
||||
|
@ -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)
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user