0
votes

I have an sql structure like so:

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
);

What sql do I need to write, how can I tell gorm that I want a Resource to have many Tags? This is what I have currently go-wise:

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:""`
}

Note that I explicitly do not want to auto-migrate via gorm. I am using the migrate tool to handle migrations and want to specifically handle them manually, not with go.

1

1 Answers

1
votes

To define a has many relationship, a foreign key must exist.

So for your case Tag should be:

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

and Resource:

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

And your sql structure should have that foreign key ResourceID column.

Not sure if you have already checked this but it contains more details in case you need them: https://gorm.io/docs/has_many.html#Foreign-Key