Answers for "gorm example onerealation golang"

Go
0

gorm example onerealation golang

package models

import (
	"time"
)

// ####################
//  Student Model
// ####################

type EntityStudent struct {
	ID        uint32 `gorm:"primary_key:auto_increment"`
	Name      string `gorm:"type:varchar;not null"`
	Npm       uint64 `gorm:"type:integer;not null;unique"`
	Fak       string `gorm:"type:varchar;not null"`
	Bid       string `gorm:"type:varchar;not null"`
	TeacherID uint32 `gorm:"column:teacher_id"`
	Teacher   EntityTeacher
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (m *EntityStudent) BeforeCreate() {
	m.CreatedAt = time.Now().Local()
}

func (m *EntityStudent) BeforeUpdate() {
	m.UpdatedAt = time.Now().Local()
}

// ####################
//  Teacher Model
// ####################

type EntityTeacher struct {
	ID        uint32          `gorm:"primary_key:auto_increment"`
	Name      string          `gorm:"type:varchar; not null"`
	StudentID uint32          `gorm:"column:student_id"`
	Students  []EntityStudent `gorm:"Foreignkey:TeacherID"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (m *EntityTeacher) BeforeCreate() {
	m.CreatedAt = time.Now().Local()
}

func (m *EntityTeacher) BeforeUpdate() {
	m.UpdatedAt = time.Now().Local()
}
Posted by: Guest on October-05-2021

Browse Popular Code Answers by Language