go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.53k stars 3.91k forks source link

Failed to auto migrate, but got error Error 1170: BLOB/TEXT column 'user_refer' used in key specification without a key length #3369

Closed diluga closed 4 years ago

diluga commented 4 years ago

Description

when i used User.Name for primary_key,call AutoMigrate() will got error,like this:

2020/09/03 15:05:30 /Users/mybook/go/src/demo/src/db/connect.go:30 Error 1170: BLOB/TEXT column 'user_refer' used in key specification without a key length
[0.417ms] [rows:0] CREATE TABLE `credit_cards` (`number` longtext,`user_refer` longtext,CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_refer`) REFERENCES `users`(`name`))
2020/09/03 15:05:30 Failed to auto migrate, but got error Error 1170: BLOB/TEXT column 'user_refer' used in key specification without a key length

my models :

type User struct {
    Name string `gorm:"primary_key"`
    CreditCards []CreditCard `gorm:"foreignKey:UserRefer"`
}

type CreditCard struct {
    Number    string
    UserRefer string
}

ENV

gorm.io/driver/mysql v1.0.1
gorm.io/gorm v1.20.0

go version go1.14.4 darwin/amd64
github-actions[bot] commented 4 years ago

This issue has been automatically marked as stale as it missing playground pull request link, checkout https://github.com/go-gorm/playground for details, it will be closed in 2 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking

jinzhu commented 4 years ago

set size for field UserRefer, e.g:

type CreditCard struct {
    Number    string
    UserRefer string `gorm:"size:191"`
}
diluga commented 4 years ago

set size for field UserRefer, e.g:

type CreditCard struct {
  Number    string
  UserRefer string `gorm:"size:191"`
}

thx!

justincletus commented 1 year ago

set size for field UserRefer, e.g:

type CreditCard struct {
  Number    string
  UserRefer string `gorm:"size:191"`
}

@diluga Thanks this works for me too

pomozoff commented 5 months ago

What is the difference with the length attribute?