I'm trying to fetch books data that have many authors. The relationship type between them is simple Many to Many with a pivot table only consist both ID. This is the models,
package model
import "gorm.io/gorm"
type Author struct {
gorm.Model
ID uint `gorm:"primaryKey; autoIncrement" json:"id"`
Name string `gorm:"Not Null" json:"name"`
Book []*Book `gorm:"many2many:trx_book_author;" json:"books"`
}
func (author *Author) TableName() string {
return "tbl_authors"
}
package model
import "gorm.io/gorm"
type Book struct {
gorm.Model
ID uint `gorm:"primaryKey; autoIncrement" json:"id"`
Title string `gorm:"Not Null" json:"title"`
Description string `json:"description"`
PageNumber int `gorm:"Not Null" json:"page_number"`
Author []*Author `gorm:"many2many:trx_book_author;" json:"authors"`
}
func (book *Book) TableName() string {
return "tbl_books"
}
And this is the way I fetch the data,
func (bookRepository *BookRepository) GetAll() []model.Book {
var books []model.Book
bookRepository.db.Preload("Author").Find(&books)
return books
}
Whenever I hit the URL, I got bunch of data that I wanted but I want to select only 'name' column on author.
I've tried with this solution but it's not working
func (bookRepository *BookRepository) GetAll() []model.Book {
var books []model.Book
bookRepository.db.Preload("Author", func(tx *gorm.DB) *gorm.DB {
return tx.Select("name")
}).Find(&books)
return books
}
any idea ?
EDIT 1: This is the error produced when using tx.Select("name") or ("Name")
failed to assign association &model.Author{Model:gorm.Model{ID:0x0, CreatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), UpdatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), DeletedAt:gorm.DeletedAt{Time:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), Valid:false}}, ID:0x0, Name:"dowjqdiq", Book:[]*model.Book(nil)}, make sure foreign fields exists; failed to assign association &model.Author{Model:gorm.Model{ID:0x0, CreatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), UpdatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), DeletedAt:gorm.DeletedAt{Time:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), Valid:false}}, ID:0x0, Name:"ddqw", Book:[]*model.Book(nil)}, make sure foreign fields exists; failed to assign association &model.Author{Model:gorm.Model{ID:0x0, CreatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), UpdatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), DeletedAt:gorm.DeletedAt{Time:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), Valid:false}}, ID:0x0, Name:"vevebe", Book:[]*model.Book(nil)}, make sure foreign fields exists
[24.020ms] [rows:5] SELECT * FROM `tbl_books` WHERE `tbl_books`.`deleted_at` IS NULL