Didn't get Delete User records based on ID - go

I'm using Go with Gorm many2many association from User and Role tables.
type User struct {
//gorm.Model
ID int64 `json:"id" gorm:"primary_key"`
Active sql.NullString ` json:"active " `
Email string `json:"email"`
FullName string `json:"full_name"`
Password string `json:"password"`
Username string `json:"username"`
Groups string `json:"groups"`
Otp string `json:"otp"`
CreatedTimeStamp time.Time `json:"created_time_stamp"`
UpdateTimeStamp time.Time `json:"update_time_stamp"`
LastLogin time.Time `json:"last_login"`
UserCount uint `json:"user_count" `
Roles []Role `gorm:"many2many:user_roles;"`
}
type Role struct {
//gorm.Model
ID int64 `json:"id" gorm:"primary_key"`
Name string `json:"name"`
Users []User `gorm:"many2many:user_roles"`
}
using below code for delete user records and roles based on user id.
var roles []Role
db.Model(Role{}).Where("Name = ?", "ROLE_ADMIN").Take(&roles)
newUser := &User{
Email: user.Email,
FullName: user.FullName,
Username: user.Username,
Groups: groupCreation(user.Username),
Password: EncodePassword(user.Password),
CreatedTimeStamp: time.Now(),
UpdateTimeStamp: time.Now(),
LastLogin: time.Now(),
Roles: roles
}
db.Save(newUser)
**db.Model(&user).Association("Role").Delete(&newUser)**
Once executed last statement but didn't get delete(no impact) records from tables users and user_roles.
Kindly suggest me what is issue.

This code:
db.Model(&user).Association("Role").Delete(&newUser)
by the Gorm documentation:
Remove the relationship between source & arguments if exists, only delete the reference, won’t delete those objects from DB.
You need to use the Delete with Select https://gorm.io/docs/associations.html#Delete-with-Select
So actually it should be:
db.Select("Role").Delete(&newUser)

Related

Associations not working with test entries

I have two models User and Address in GORM defined:
File user.go
type User struct {
gorm.Model
Identity string `json:"identity"`
Password string `json:"password"`
Address Address
AddressID int
}
type Address struct {
gorm.Model
Street string `json:"street"`
StreetNumber string `json:"streetnumber"`
}
In the main.go file I initiate the DB, automigrate and want to add a test user to the DB:
database.InitDatabase()
database.DBConn.AutoMigrate(&user.User{})
database.DBConn.AutoMigrate(&user.Address{})
userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Address: user.Address{Street: "Teststreet", StreetNumber: "1"}}
database.DBConn.Create(userRec)
The user gets created and the address as well, however, the address is not associated with the user, just
empty Address fields come up. What did I forget?
Is this the normal way to setup a test entry if you have associations in your entities (with nested models)?
Try using the "address_id" field as a foreignKey.
for example
type User struct {
gorm.Model
Identity string `json:"identity"`
Password string `json:"password"`
Address Address `gorm:"foreignKey:address_id;association_autoupdate:false"`
AddressID uint `json:"address_id"`
}
Online documentation
Maybe it will help.

Gorm extra where 1 <> 1 in many2many

I have two models (structs). User and Group. Those models have many to many relationships.
When I try to create query db.Unscoped().Model(&group).Related(&users, "Users") this returns:
SELECT users.* FROM users INNER JOIN user_groups ON user_groups.owner_id = users.id WHERE (1 <> 1)
The entities are:
type Group struct {
gorm.Model
ID uint `json:"id"`
Name string `json:"name"`
Users []User `gorm:"many2many:user_groups;association_jointable_foreignkey:owner_id"`
}
type User struct {
...
Groups []Group `gorm:"many2many:user_groups;association_jointable_foreignkey:group_id"`
}
Handler
users := []models.User{}
group := models.Group{}
db.Unscoped().Model(&group).Related(&users, "Users")
I don't know the reason to generate extra where.
The problem is fixed.
I have eliminated gorm.Model in struct:
type Group struct {
ID uint `json:"id"`
Name string `json:"name"`
Users []User `gorm:"many2many:user_groups;association_jointable_foreignkey:owner_id"`
}
And In the query:
db.Model(&group).Related(&users)
Regards.

How to set unique at struct Beego

How to set unique at the struct specific columns. first name
type User struct {
ID int64 `orm:"size(100)", pk`
Lastname string `orm:"size(100)"`
Firstname string `orm:"size(100)"`
Role string `orm:"size(100)"`
Created time.Time `orm:"size(100)"`
Updated time.Time `orm:"size(100)"`
}
I'm using "github.com/astaxie/beego/orm"
According to the documentation, you just add the word "unique" to the tag:
Add unique key for one field
Name string `orm:"unique"`
To combine tags, you must use a semicolon as documented here. For example:
Firstname string orm:"unique;size(100)"

Referencing GORM auto-generated fields in Go

I'm writing my first API, so bear with me. I am using Go, Postgres and GORM and a slew of other things I'm still picking up but I ran into an issue with GORM's AutoMigrate.
Initially my User struct looked like this:
type User struct {
gorm.Model
Email string `gorm:"unique" json:"email"`
Password string `json:"password"`
}
And when I ran db.AutoMigrate(&User{}) It auto-generated an id field in my User table (along with several date fields), which I wanted. What I am hung up on is figuring out how to reference these fields in my app. I have modified my User struct to now look like this:
type User struct {
gorm.Model
ID int `gorm:"primary_key" json:"id"`
Email string `gorm:"unique" json:"email"`
Password string `json:"password"`
}
But instead of linking the two id fields, when I access the stored user object as shown:
user := model.User{}
if err := db.First(&user, model.User{Email: email}).Error; err != nil {
respondError(w, http.StatusNotFound, err.Error())
return nil
}
there are now two distinct fields, the auto-generated and my own:
{
"ID": 2,
"CreatedAt": "2018-04-28T21:14:20.828547-04:00",
"UpdatedAt": "2018-04-28T21:14:20.828547-04:00",
"DeletedAt": null,
"id": 0,
"email": "joeynelson#gmail.com",
"password": <hash>
}
I realize the answer is likely right in front of my face, there must be a way to reference these auto-generated fields, right?
gorm.Model is a struct including some basic fields, which including fields ID, CreatedAt, UpdatedAt, DeletedAt.
Reference: http://gorm.io/docs/conventions.html#gorm-Model

How can I remove a 'Belongs To' association in jinzhu/gorm

Can anyone help me, how to remove a belongs to association in go-gorm?
Here are my simple models:
type User struct {
gorm.Model
Name string
FirstName string
}
type Customer struct {
Notes []Note `gorm:"polymorphic:Owner;"` // other models can have notes as well
}
type Note struct {
gorm.Model
User User `json:"-"`
UserID uint
OwnerID uint
OwnerType string
}
For "Has many" and "Many to many" associations I can remove the relations. In this example, this works:
db.Model(&customer).Association("Notes").Delete(&note)
However, if I try following:
db.Model(&note).Association("User").Delete(&user)
I get a pointer error:
panic: runtime error: index out of range
... src/github.com/jinzhu/gorm/association.go:242 +0x21ce
The ''user'' and ''note'' objects exist and the relation is there (UserID is set to 1 in the database).

Resources