Computer scienceProgramming languagesGolangWorking with dataRelational databasesGORM

Relationships between models

Declaring models for the library database

Report a typo

Stephen wants to create a new in-memory library.db SQLite database that contains the authors, books and publishers tables. Then, he wants to set up a one-to-many relationship between the publishers and books tables, and a many-to-many relationship between authors and books tables.

The authors table should have the following columns:

authors
id INTEGER, PK
created_at DATETIME
updated_at DATETIME
deleted_at DATETIME
name TEXT

And the books table should have the following columns:

books
id INTEGER, PK
created_at DATETIME
updated_at DATETIME
deleted_at DATETIME
title TEXT
date_published DATETIME
publisher_id INTEGER, FK(publishers)

The publishers table should have the following columns:

publishers
id INTEGER, PK
created_at DATETIME
updated_at DATETIME
deleted_at DATETIME
name TEXT

And the author_books join table (which is automatically created by GORM) should have the following columns:

author_books
author_id INTEGER, FK(authors)
book_id INTEGER, FK(books)

Your task is to help Stephen write the required code to declare the Author, Book and Publisher models, using the gorm.Model struct, and set up the relationships between them; apart from that, use the `gorm:"many2many:..."` struct tag to set up the many-to-many relationship between Author and Books and create the author_books join table.

This problem uses the reflect package and the hidden function checkModels() to check if you correctly declared the Author, Book and Publisher models and adequately set up the relationships between them.
Write a program in Go
package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
"reflect"
"strings"
"time"
"unicode"
)

// Declare the `Author` model below:
type Author struct {
gorm.Model
? ?
? []Book `gorm:"?:author_books"`
}

// Declare the `Book` model below:
type Book struct {
?
? ?
DatePublished ?
PublisherID ?
Authors []? `gorm:"many2many:?"`
}

// Declare the `Publisher` model below:
type Publisher struct {
?
? ?
Books []?
}

___

Create a free account to access the full topic