I'm using gorm and postgresql for a side-project, and I don't know how to solve this problem in 1 request:
My User type is the following:
type User struct {
UserId string
Email string
FirstName string
LastName string
Phone string
Address_1 string
Address_2 string
City string
State string
Zip string
Gender string
ImageUri string
Roles []Role `gorm:"foreignkey:UserId"`
}
My Role type is the following:
type Role struct {
UserId string
Role string
}
I want to get all users with their associated roles, but right now i'm doing this with 2 requests and I want to do it only with one:
func (s *Store) ListUsers() ([]User, error) {
users := []User{}
if err := db.Joins("join roles ON roles.user_id = users.user_id").Find(&users).Error; err != nil {
return nil, err
}
for i, user := range users {
roles := []Role{}
if err := db.Where("user_id = ?", user.UserId).Model(&Role{}).Find(&roles).Error; err != nil {
return User{}, errors.Wrap(err, "failed to get roles")
}
users[i].Roles = roles
}
return users, nil
}
I tried with several different requests, using Related etc... but my Roles slice is always empty. Any ideas ?
[EDIT] My sql schema
CREATE TABLE IF NOT EXISTS users (
user_id varchar PRIMARY KEY UNIQUE NOT NULL,
email varchar UNIQUE NOT NULL,
first_name varchar,
last_name varchar,
phone varchar,
address_1 varchar,
address_2 varchar,
city varchar,
state varchar,
zip varchar,
gender varchar,
image_uri varchar
);
CREATE TABLE IF NOT EXISTS roles (
user_id varchar REFERENCES users (user_id) ON DELETE CASCADE,
role varchar NOT NULL
);
There #har07 soultions it's probably what you need db.Preload("Roles").Find(&users) but you can't get Roles because you don't have primary key declared in you user struct, so at the end your user should look like this:
type User struct {
UserId string `gorm:"primary_key"`
Email string
FirstName string
LastName string
Phone string
Address_1 string
Address_2 string
City string
State string
Zip string
Gender string
ImageUri string
Roles []Role `gorm:"foreignkey:UserId"`
}
Related
I keep receiving this error:
insert or update on table "note" violates foreign key constraint "note_username_fkey"
I have two tables: User and Note. Here are the create table statements:
func setup() *sql.DB {
db = connectDatabase()
//Create queries
userTable := `CREATE TABLE IF NOT EXISTS "User"(
UserID SERIAL unique,
UserName VARCHAR(50) PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Password VARCHAR(40)
);`
noteTable := `CREATE TABLE IF NOT EXISTS Note(
NoteID SERIAL PRIMARY KEY,
UserID INT,
UserName VARCHAR(50),
Title VARCHAR(30),
Contents VARCHAR(1000),
DateCreated DATE,
DateUpdated DATE,
FOREIGN KEY (UserName) REFERENCES "User"(UserName)
);`
}
func createNoteInsertSQL(userID string, userName string, title string, content string, selectSetting string) bool {
var newNote Note
var err error
newNote.UserID, err = strconv.Atoi(userID)
if err != nil {
log.Fatal(err)
}
newNote.UserName = userName
newNote.Title = title
newNote.Contents = content
date := time.Now()
newNote.DateCreated = date
newNote.DateUpdated = date
query := `INSERT INTO Note (UserID, UserName, Title, Contents, DateCreated, DateUpdated) VALUES ($1, $2, $3, $4, $5, $6) RETURNING NoteID;`
stmt, err := db.Prepare(query)
if err != nil {
log.Fatal(err)
return false
}
var noteID int
err = stmt.QueryRow(newNote.UserID, newNote.UserName, newNote.Title, newNote.Contents, newNote.DateCreated, newNote.DateUpdated).Scan(¬eID)
if err != nil {
log.Fatal(err)
return false
}
}
Can anyone please tell me where the wrong ?
Thanks.
Check whether "Username" column value you try to insert in note table is already available in "User" table. Because the insert query is trying to insert value that is not available in "User" table.
i am trying to do a left join on query but i have an invalid reference to FROM-Clause
here are the structure of the code
this is the product table
CREATE TABLE products
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR(255),
productdesc TEXT,
costprice DOUBLE PRECISION,
recommendprice DOUBLE PRECISION,
views BIGINT DEFAULT 0,
enabled BOOLEAN DEFAULT FALSE,
category_id BIGINT REFERENCES categories (id) ON DELETE CASCADE NOT NULL,
)
this is the category table
CREATE TABLE categories
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
pid BIGINT NOT NULL,
title VARCHAR(255),
image VARCHAR(255),
);
this is the type struct
type Product struct {
TableName struct{} `sql:"products"`
ID int64 `json:"id"`
TITLE string `json:"title"`
PRODUCTDESC string `json:"product_desc"`
COSTPRICE float64 `json:"costprice"`
RECOMMENDPRICE float64 `json:"recommendprice"`
VIEWS int64 `json:"views"`
ENABLED bool `json:"enabled"`
CATEGORYNAME string `json:"categoryname"`
}
type Category struct {
tableName struct{} `pg:"categories"`
ID int64 `json:"id"`
Title string `json:"title"`
Image string `json:"image"`
}
this is the actual query to database
func (t *ProductRepo) GetAllProducts() ([]*domain.Product, error) {
var products []*domain.Product
query := t.DB.Model(&products).
ColumnExpr("products.*").
ColumnExpr("c.id AS category_id, c.title AS categoryname").
Join("LEFT JOIN categories AS c ON c.id = products.category_id")
err := query.Select()
if err != nil {
return nil, err
}
return products, nil
}
this is the actual error from postman
{
"error": "ERROR #42P01 invalid reference to FROM-clause entry for table \"products\""
}
any help would be great,
thanks advance
Jason
I am trying to load one to one and one to many associations for one of my object using GORM. I keep getting the following error when I am trying to run.
{
"errors": [
{
"message": "can't preload field UserProfiles for models.Renter",
"path": [
"users"
]
}
],
"data": null
}
Here is my code
type User struct {
BaseModelSoftDelete // We don't to actually delete the users, audit
Email string `gorm:"not null;unique_index"`
Password string
FirstName *string
LastName *string
Renter Renter `gorm:"auto_preload"`
Rentee Rentee `gorm:"auto_preload"`
UserProfiles []UserProfile `gorm:"association_autocreate:false;association_autoupdate:false"`
Roles []Role `gorm:"many2many:user_roles;association_autocreate:false;association_autoupdate:false"`
Permissions []Permission `gorm:"many2many:user_permissions;association_autocreate:false;association_autoupdate:false"`
}
// UserProfile saves all the related OAuth Profiles
type UserProfile struct {
BaseModelSeq
Email string `gorm:"unique_index:idx_email_provider_external_user_id"`
UserID uuid.UUID `gorm:"not null;index"`
User User `gorm:"association_autocreate:false;association_autoupdate:false"`
Provider string `gorm:"not null;index;unique_index:idx_email_provider_external_user_id;default:'DB'"` // DB means database or no ExternalUserID
ExternalUserID string `gorm:"not null;index;unique_index:idx_email_provider_external_user_id"` // User ID
Name string
FirstName string
LastName string
AvatarURL string `gorm:"size:1024"`
Description string `gorm:"size:1024"`
}
type Renter struct {
BaseModelSoftDelete // We don't to actually delete the users, audit
UserID uuid.UUID `gorm:"unique;not null;index"`
Verified bool
Properties []Property `gorm:"association_autocreate:false;association_autoupdate:false"`
Listings []Listing `gorm:"association_autocreate:false;association_autoupdate:false"`
}
type Rentee struct {
BaseModelSoftDelete // We don't to actually delete the users, audit
UserID uuid.UUID `gorm:"unique;not null;index"`
Verified bool
Bookings []Booking `gorm:"association_autocreate:false;association_autoupdate:false"`
}
then I call this function
func userList(r *queryResolver, id *string) (*gql.Users, error) {
entity := consts.GetTableName(consts.EntityNames.Users)
whereID := "id = ?"
record := &gql.Users{}
dbRecords := []*dbm.User{}
tx := r.ORM.DB.Begin().Preload(consts.EntityNames.UserProfiles)
defer tx.RollbackUnlessCommitted()
if id != nil {
tx = tx.Where(whereID, *id)
}
tx = tx.Find(&dbRecords).Count(&record.Count)
for _, dbRec := range dbRecords {
renter := dbm.Renter{}
tx = tx.Model(&dbRec).Related(&renter)
logger.Infof("%+v", dbRec.Renter)
// rentee := dbm.Rentee{}
// tx.Related(&rentee)
// logger.Info(rentee)
if rec, err := tf.DBUserToGQLUser(dbRec); err != nil {
logger.Errorfn(entity, err)
} else {
record.List = append(record.List, rec)
}
}
return record, tx.Error
}
If I get rid of tx = tx.Model(&dbRec).Related(&renter) the query runs, the profile object loads but my renter and rentee object doesn't have the data from database. And I notice it doesn't run the query SELECT * FROM "renters" WHERE "renters"."deleted_at" IS NULL AND (("user_id" = 'my-user-uuid'))
I also tried to this this:
tx = tx.Preload(consts.EntityNames.Renters).Preload(consts.EntityNames.Rentees).Preload(consts.EntityNames.UserProfiles).Find(&dbRecords).Count(&record.Count)
but get thise error: can't preload field Renters for models.User
I have People and Data , where People has one Data and Data belongs to People
how to make a request body JSON for that Association in go gin? I am using gorm for this case,
the documentation of gorm is not clear for me for this case,
i was supposed like
func CreateTodo(db *gorm.DB) func(c *gin.Context) {
var person Person
var data Data
c.bindJSON(&Person)
c.bindJSON(&Data)
db.create(&Person)
db.create(&Data)
c.JSON(200, gin.H{ result : []interface{person, data})
}
type (
Data struct {
ID uint `gorm:"auto_increment"`
PersonID uint
Person *Person `gorm:"foreignkey:PersonID;association_foreignkey:id"`
Address string
Languange string
}
Person struct {
gorm.Model
Email string `gorm:"type:varchar(100);unique_index;not null"`
Password string `gorm:"type:varchar(100);not null"`
Role string `gorm:"size:30;not null"`
DataID uint
Data *Data `gorm:""foreignkey:DataID;association_foreignkey:id"`
}
)
I am sure it will not make the person_id and data_id for FK
what I ask, how I can make the request body for that Association until those request created with FK itself ? should I create then update again for person_id and data_id after it created ??
Gorm will do almost everything for an association link. It seems that "DataID" in your Person struct is useless. See the code below for an example:
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type (
Data struct {
ID uint `gorm:"auto_increment"`
PersonID uint
Person *Person `gorm:"foreignkey:PersonID;association_foreignkey:id"`
Address string
Languange string
}
Person struct {
gorm.Model
Email string `gorm:"type:varchar(100);unique_index;not null"`
Password string `gorm:"type:varchar(100);not null"`
Role string `gorm:"size:30;not null"`
Data *Data `gorm:""foreignkey:PersonID;association_foreignkey:id"`
}
)
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
db.LogMode(true)
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Person{}, &Data{})
data := &Data{
Address: "Shanghai,China",
Languange: "Chinese",
}
person := &Person{
Email: "zhjw43#163.com",
Data: data,
}
db.Save(person)
db.DropTable("data", "people")
}
I'm trying to create a basic commenting api in go. I can't seem to figure out how to scan postgresql arrays into an array of structs within a struct. I think I could probably have Thread.Posts type be jsonb but that seems inelegant since I would have to unmarshall it I think.
sql: Scan error on column index 3, name "posts": unsupported Scan,
storing driver.Value type []uint8 into type *[]models.Post
var threadSchema = `
CREATE TABLE IF NOT EXISTS thread (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
profile_id INTEGER REFERENCES profile (id)
)`
var postSchema = `
CREATE TABLE IF NOT EXISTS post (
id SERIAL PRIMARY KEY,
comment TEXT,
profile_id INTEGER REFERENCES profile (id),
thread_id INTEGER REFERENCES thread (id)
)`
type Post struct {
Id int `db:"id" json:"id"`
Comment string `db:"comment" json:"comment" binding:"required" form:"comment"`
ProfileId int `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
ThreadId int `db:"thread_id" json:"thread_id" binding:"required" form:"thread_id"`
}
type Thread struct {
Id int `db:"id" json:"id"`
Name string `db:"name" json:"name" binding:"required" form:"name"`
ProfileId int `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
Posts []Post `db:"posts" json:"posts" form:"posts"`
}
func GetThreads(db *sqlx.DB, c *gin.Context) {
threads := []Thread{}
err := db.Select(&threads, `
SELECT thread.id,thread.name,thread.profile_id,array_agg(post.id) AS posts
FROM thread
INNER JOIN post ON thread.id = post.thread_id
GROUP BY thread.id;
`)
if err != nil {
log.Fatal(err)
}
c.JSON(http.StatusOK, gin.H{"data": threads})
}
You could define your type:
type Posts []Post
// Scan implements the sql.Scanner interface.
func (a *Posts) Scan(src interface{}) error {
// ...
}
// Value implements the driver.Valuer interface.
func (a Posts) Value() (driver.Value, error) {
// ...
}
For more information on the implementation see eg here
First off, you can't do this with sqlx, whether or not you're using Postgres arrays.
Second, your SQL query is simply aggregating Post IDs, not the content of the posts, so there's no way to get the data you want (using Go or otherwise).
So here's what you can do:
Use an anonymous embedded struct, capture all of the Post content in your SQL query, and then merge your duplicated Threads.
type Post struct {
Id int `db:"id" json:"id"`
Comment string `db:"comment" json:"comment" binding:"required" form:"comment"`
ProfileId int `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
ThreadId int `db:"thread_id" json:"thread_id" binding:"required" form:"thread_id"`
}
type ThreadDb struct {
Id int `db:"id" json:"id"`
Name string `db:"name" json:"name" binding:"required" form:"name"`
ProfileId int `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
Post
}
type Thread struct {
Id int `db:"id" json:"id"`
Name string `db:"name" json:"name" binding:"required" form:"name"`
ProfileId int `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
Posts []Post `db:"posts" json:"posts" form:"posts"`
}
func GetThreads(db *sqlx.DB, c *gin.Context) {
threads := []ThreadDb{}
err := db.Select(&threads, `
SELECT thread.id,thread.name,thread.profile_id,post.id,post.comment,post.profile_id,post.thread_id
FROM thread
INNER JOIN post ON thread.id = post.thread_id
GROUP BY post.id;
`)
thread_map := make(map[string]Thread)
for i, thread := range threads {
if _, ok := thread_map[thread.Id]; ok {
thread_map[thread.Id].Posts = append(thread_map[thread.Id].Posts, thread.Post)
} else {
thread_map[thread.Id] = Thread{thread.Id, thread.Name, thread.ProfileId, []Post{thread.Post}}
}
}
var threadSlice []string
for k := range thread_map {
threadSlice = append(threadSlice, k)
}
if err != nil {
log.Fatal(err)
}
c.JSON(http.StatusOK, gin.H{"data": threadSlice})
}
Use GROUP_CONCAT or similar. I wouldn't recommend unless you plan on having a maximum of about 100 posts per thread.