Golang Gorm one-to-many relationship table creation

one-to-many relationship


Let's start with one-to-many to learn about multi-table relationships because one-to-many relationships are everywhere in life, for example:

  • boss and employee
  • Goddess and Tim Dog
  • teacher and student
  • Classes and Students
  • Users and Articles

When creating, first create without dependencies. The table name + ID is the foreign key. The data type of the foreign key must be consistent with that of the associated foreign key.

package main

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

// User 用户表 一个用户拥有多篇文章
type User struct {
	ID       int64
	Name     string    `gorm:"size:6"`
	Articles []Article //用户拥有的文章列表 has many
}

type Article struct {
	ID     int64  `gorm:"size:4"`
	Title  string `gorm:"size:16"`
	UserID int64  //属于  belongs to  这里的类型要和引用的外键类型一致
	User   User   //属于
}

func (*User) TableName() string {
	return "user"
}

func (*Article) TableName() string {
	return "article"
}


func main() {
	dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	db.Debug().AutoMigrate(&User{}, &Article{})
}

[52.373ms] [rows:0] CREATE TABLE `user` (`id` bigint AUTO_INCREMENT,`name` varchar(6),PRIMARY KEY (`id`))


[30.441ms] [rows:0] CREATE TABLE `article` (`id` tinyint AUTO_INCREMENT,`title` varchar(16),`user_id` bigint,PRIMARY KEY (`id`),CONSTRAINT `fk_user_
articles` FOREIGN KEY (`user_id`) REFERENCES `user`(`id`))

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132444861