努力手动创建与 gorm / migrate 的关系

Struggling to manually create relations with gorm / migrate

我有一个像这样的 sql 结构:

CREATE TABLE resources (
  id SERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL,
  deleted_at TIMESTAMPTZ
);

CREATE TABLE tags (
    name TEXT PRIMARY KEY
);

我需要写什么sql,我怎么告诉gorm我想要一个Resource有很多Tag?这就是我目前所拥有的:

package models

import (
    "github.com/jinzhu/gorm"
)

type Tag struct {
    Name string `gorm:"PRIMARY_KEY"`
}

type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:""`
}

请注意,我明确想通过 gorm 自动迁移。我正在使用 migrate 工具来处理迁移,并希望专门手动处理它们,而不是使用 go。

要定义有多个关系,必须存在外键。

所以对于你的案例,标签应该是:

type Tag struct {
    gorm.Model
    Name string `gorm:"PRIMARY_KEY"`
    ResourceID int
}

和资源:

type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:"foreignkey:ResourceID"`
}

并且您的 sql 结构应该有外键 ResourceID 列。

不确定您是否已经检查过这个,但它包含更多详细信息以备您需要时使用:https://gorm.io/docs/has_many.html#Foreign-Key