Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

id 字段被强制设置成主键问题 #7323

Open
mmggzz opened this issue Dec 20, 2024 · 0 comments
Open

id 字段被强制设置成主键问题 #7323

mmggzz opened this issue Dec 20, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@mmggzz
Copy link

mmggzz commented Dec 20, 2024

Your Question

表中有一个 id 字段,我并不想将它设置为主键,因此,我设置了 primaryKey:false,但是不起作用。

type Test struct {
	ID  int64 `gorm:"autoIncrement:false;primaryKey:false;column:id;type:bigint;not null" json:"-"` 
}

查看源码后,发现了这一段:

	prioritizedPrimaryField := schema.LookUpField("id")
	if prioritizedPrimaryField == nil {
		prioritizedPrimaryField = schema.LookUpField("ID")
	}

	if prioritizedPrimaryField != nil {
		if prioritizedPrimaryField.PrimaryKey {
			schema.PrioritizedPrimaryField = prioritizedPrimaryField
		} else if len(schema.PrimaryFields) == 0 {
			prioritizedPrimaryField.PrimaryKey = true
			schema.PrioritizedPrimaryField = prioritizedPrimaryField
			schema.PrimaryFields = append(schema.PrimaryFields, prioritizedPrimaryField)
		}
	}

我不明白 else if len(schema.PrimaryFields) == 0 都明确表示没有主键字段了,为什么硬是要塞一个 id 字段作为主键?

Expected answer

设置 primaryKey:false 后,不管是不是 id 字段,都不应该将字段设置为主键。

@mmggzz mmggzz added the type:question general questions label Dec 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants