GORM [错误] 不支持的数据类型: &[], 错误的模式

huangapple go评论111阅读模式
英文:

GORM [error] unsupported data type: &[], incorrect schema

问题

GORM v1.25.1,我正在尝试在WorkerPosterJob模型上运行DB.AutoMigrate(),但遇到了[error] unsupported data type: &[]的问题。Worker和Job结构体应该具有多对多关系,而Poster和Job应该具有一对多关系。Worker和experience、worker和preference都应该是一对多关系。请帮忙解决。

package model

type experience struct {
	gorm.Model
	Company  int    `json:"company"`
	JobTitle string `json:"jobTitle"`
	WorkerID uint
}

type preference struct {
	gorm.Model
	JobTitle string `json:"JobTitle"`
	MinPay   int    `json:"minPay"`
	MaxPay   int    `json:"maxPay"`
	WorkerID uint
}

type Worker struct {
	gorm.Model
	Username     string       `gorm:"uniqueIndex;not null" json:"username"`
        ...更多字段
	Experience   []experience `json:"experience"`
	Preference   []preference `json:"preference"`
	AppliedJobs  []Job        `gorm:"many2many:worker_jobs;" json:"appliedJobs"`
}

type Poster struct {
	gorm.Model
	Name       string `gorm:"uniqueIndex;not null" json:"name"`
	Email      string `gorm:"uniqueIndex;not null" json:"email"`
	Phone      string `json:"phone"`
	JobsPosted []Job  `json:"jobsPosted"`
}

type Job struct {
	gorm.Model
	Title       string   `gorm:"uniqueIndex;not null" json:"title"`
        ...更多字段
	PosterID uint `json:"posterID"`
}
英文:

GORM v1.25.1, I'm tryping to run DB.AutoMigrate() on Worker, Poster and Job models but running into [error] unsupported data type: &[]. The Worker and Job struct should have a many-to-many relation, while Poster and Job should have one-to-many relation. Worker and experience, worker and preference both should be a one-to-many relation. Please help.

package model

type experience struct {
	gorm.Model
	Company  int    `json:"company"`
	JobTitle string `json:"jobTitle"`
	WorkerID uint
}

type preference struct {
	gorm.Model
	JobTitle string `json:"JobTitle"`
	MinPay   int    `json:"minPay"`
	MaxPay   int    `json:"maxPay"`
	WorkerID uint
}

type Worker struct {
	gorm.Model
	Username     string       `gorm:"uniqueIndex;not null" json:"username"`
        ...more fields
	Experience   []experience `json:"experience"`
	Preference   []preference `json:"preference"`
	AppliedJobs  []Job        `gorm:"many2many:worker_jobs;" json:"appliedJobs"`
}

type Poster struct {
	gorm.Model
	Name       string `gorm:"uniqueIndex;not null" json:"name"`
	Email      string `gorm:"uniqueIndex;not null" json:"email"`
	Phone      string `json:"phone"`
	JobsPosted []Job  `json:"jobsPosted"`
}

type Job struct {
	gorm.Model
	Title       string   `gorm:"uniqueIndex;not null" json:"title"`
        ...more fields
	PosterID uint `json:"posterID"`
}

答案1

得分: 1

我能够使用以下代码实现你所需的功能。

请注意,为了演示的目的,我简化了你的模型(结构体),只包含与关联相关的字段。如果我遗漏了值得一提的内容,请随时提问,我会更新我的回答。

首先让我分享代码,然后我会详细解释它。

package main

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Worker struct {
	gorm.Model
	Username string `gorm:"uniqueIndex;not null" json:"username"`

	Posters []Poster `gorm:"many2many:workers_posters;joinForeignKey:postersId"`
}

type Poster struct {
	gorm.Model
	Name  string `gorm:"uniqueIndex;not null" json:"name"`
	Email string `gorm:"uniqueIndex;not null" json:"email"`
	Phone string `json:"phone"`

	Workers []Worker `gorm:"many2many:workers_posters;joinForeignKey:workersId"`
	Jobs    []Job
}

type Job struct {
	gorm.Model
	Title    string `gorm:"uniqueIndex;not null" json:"title"`
	PosterID uint   `json:"posterID"`
}

func main() {
	dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn))
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(&Worker{}, &Poster{}, &Job{})
}

由于你的问题涉及到many2manyone2many关系,我将把我的回答分为两部分。

many2many关系

要实现这种关系,你需要在保存关联实体的切片旁边添加注释gorm:"many2many:workers_posters;joinForeignKey:workersId"。受影响的字段包括:

  • Worker结构体中的Posters字段
  • Poster结构体中的Workers字段

显然,你需要根据要设置的字段更改joinForeignKey的值。

one2many关系

这种关系更简单,因为你不需要指定在many2many关联中要创建的连接表(例如上面创建的workers_posters表)。在这里,你只需要进行以下两个更改:

  1. Poster结构体中添加Jobs []Job字段
  2. Job结构体中添加PosterID uint字段

通过这样做,如果你运行Automigrate方法,你将在数据库中看到正确的表,并且所有外键都正确设置。

如果有任何问题,请告诉我,谢谢!

英文:

I was able to achieve what you need with the following code.
> Please note that, for the sake of the demo, I simplified your models (structs) by including only the relevant fields for the associations. If I omitted something worth mentioning, feel free to ask for it and I'll update my answer.

Let me first share the code, then I'll explain it in detail.

package main

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Worker struct {
	gorm.Model
	Username string `gorm:"uniqueIndex;not null" json:"username"`

	Posters []Poster `gorm:"many2many:workers_posters;joinForeignKey:postersId"`
}

type Poster struct {
	gorm.Model
	Name  string `gorm:"uniqueIndex;not null" json:"name"`
	Email string `gorm:"uniqueIndex;not null" json:"email"`
	Phone string `json:"phone"`

	Workers []Worker `gorm:"many2many:workers_posters;joinForeignKey:workersId"`
	Jobs    []Job
}

type Job struct {
	gorm.Model
	Title    string `gorm:"uniqueIndex;not null" json:"title"`
	PosterID uint   `json:"posterID"`
}

func main() {
	dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn))
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(&Worker{}, &Poster{}, &Job{})
}

As your question involve both the many2many and the one2many relationship, I'm gonna divide my answer into two parts.

The many2many relationship

To achieve this relationship, you've to add the annotation gorm:"many2many:workers_posters;joinForeignKey:workersId" next to the slices that hold associated entities. The affected fields are:

  • Posters field within the Worker struct
  • Workers field within the Poster struct

Obviously, you've to change the value for the joinForeignKey depending on what field you're about to set.

The one2many relationship

This relationship is even simpler as you don't have to specify the join table that has to be created in a many2many association (e.g. the above created workers_posters table). Here, you only have to do these two changes:

  1. Add the Jobs []Job field within the Poster struct
  2. Add the PosterID uint field within the Job struct

Thanks to this, if you run the Automigrate method, you'll see the right tables in the database with all of the foreign keys correctly set up.

Let me know, thanks!

huangapple
  • 本文由 发表于 2023年6月14日 20:23:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76473524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定