Fetch Data using One To Many Relationship in GORM

Make sure Git is installed on your machine and in your system’s PATH. Install the package to your $GOPATH with the go tool from shell:

$ go get github.com/go-sql-driver/mysql
$ go get -u github.com/jinzhu/gorm




Create a database with the name is learngorm. This database have 1 tables: Product table.

--
-- Table structure for table `faculty`
--

CREATE TABLE `faculty` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `faculty`
--

INSERT INTO `faculty` (`name`) VALUES
('Faculty 1'),
('Faculty 2'),
('Faculty 3');

--
-- Table structure for table `student`
--

CREATE TABLE `student` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `address` varchar(250) NOT NULL,
  `faculty_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `student`
--

INSERT INTO `student` (`name`, `address`, `faculty_id`) VALUES
('Name 1', 'Address 1', 1),
('Name 2', 'Address 2', 1),
('Name 3', 'Address 3', 2),
('Name 4', 'Address 4', 2),
('Name 5', 'Address 5', 2);




Create new folder named src. In src folder, create new folder named entities. In this folder, create new entities as below:

In entities folder, create new go file named faculty.entity.go as below:

package entities

import "fmt"

type Faculty struct {
	Id       int `gorm:"primary_key, AUTO_INCREMENT"`
	Name     string
	Students []Student `gorm:"ForeignKey:FacultyID"`
}

func (faculty *Faculty) TableName() string {
	return "faculty"
}

func (faculty Faculty) ToString() string {
	return fmt.Sprintf("id: %d\nname: %s", faculty.Id, faculty.Name)
}

In entities folder, create new go file named student.entity.go as below:

package entities

import "fmt"

type Student struct {
	Id        int `gorm:"primary_key, AUTO_INCREMENT"`
	Name      string
	Address   string
	FacultyID int `gorm:"column:faculty_id"`
	Faculty   Faculty
}

func (student *Student) TableName() string {
	return "student"
}

func (student Student) ToString() string {
	return fmt.Sprintf("id: %d\nname: %s\naddress: %s", student.Id, student.Name, student.Address)
}

In src folder, create new folder named config. In this folder, create new file named config.go, this file is used to connect mysql database:

package config

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

func GetDB() (*gorm.DB, error) {
	dbDriver := "mysql"
	dbName := "learngorm"
	dbUser := "root"
	dbPassword := "123456"
	db, err := gorm.Open(dbDriver, dbUser+":"+dbPassword+"@/"+dbName+"?charset=utf8&parseTime=True")
	if err != nil {
		return nil, err
	}
	return db, nil
}




In src folder, create new folder named models. In models folder, create new file named faculty.model.go. This file contains methods to interact with the database.

package models

import (
	"config"
	"entities"
)

type FacultyModel struct {
}

func (facultyModel FacultyModel) FindAll() ([]entities.Faculty, error) {
	db, err := config.GetDB()
	if err != nil {
		return nil, err
	} else {
		var faculties []entities.Faculty
		db.Preload("Students").Find(&faculties)
		return faculties, nil
	}
}




In src folder, create new file named main.go as below and use go run main.go command to run program:

package main

import (
	"fmt"
	"models"
)

func main() {
	var facultyModel models.FacultyModel
	faculties, _ := facultyModel.FindAll()
	for _, faculty := range faculties {
		fmt.Println(faculty.ToString())
		fmt.Println("Students: ", len(faculty.Students))
		if len(faculty.Students) > 0 {
			for _, student := range faculty.Students {
				fmt.Println(student.ToString())
				fmt.Println("=============================")
			}
		}
		fmt.Println("--------------------")
	}
}
id: 1
name: Faculty 1
Students:  2
id: 1
name: Name 1
address: Address 1
=============================
id: 2
name: Name 2
address: Address 2
=============================
--------------------
id: 2
name: Faculty 2
Students:  3
id: 3
name: Name 3
address: Address 3
=============================
id: 4
name: Name 4
address: Address 4
=============================
id: 5
name: Name 5
address: Address 5
=============================
--------------------
id: 3
name: Faculty 3
Students:  0
--------------------