Computer scienceProgramming languagesGolangWorking with dataRelational databasesGORM

Relationships between models

GORM's association mode

Report a typo

Stephen keeps working with the in-memory library.db SQLite database. He now wants to create a Go program that takes as input an author's name and then retrieves all of the author's books using db.Model() and the Association() method.

Stephen has already written some code; your task is to help him write the additional required code to chain the db.Model() and Association() methods, retrieve the author's books and then print them to the terminal.

For this task, the Author, Publisher, and Book models are already declared but are hidden, so DO NOT redeclare them! Just write the additional required code to accomplish the task described above.

Sample Input 1:

J.R.R. Tolkien

Sample Output 1:

Author J.R.R. Tolkien has written the following books:
The Hobbit
The Fellowship of the Ring
The Two Towers
The Return of the King
The Silmarillion
Beren and Lúthien
Write a program in Go
package main

import (
"bufio"
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
"os"
"time"
)

// ... `Author`, `Book`, and `Publisher` models are hidden here, DO NOT redeclare them!

func main() {
// DO NOT delete or modify the code block below:
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
must(err)
populateDatabase(db)

author, name := Author{}, getAuthorName()
result := db.First(&author, "name = ?", name)
if result.Error != nil {
log.Fatalf("cannot find author: %v", result.Error)
}

// Retrieve the author's books using `db.Model()` and `Association()` below:
var books []Book
err = db.?(&?).?("?").Find(&?)
must(err)

// DO NOT delete or modify the print statements below:
fmt.Printf("Author %s has written the following books:\n", author.Name)
for _, book := range books {
fmt.Printf("%s\n", book.Title)
}
___

Create a free account to access the full topic