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)"
Related
I have a struct snippet which is something like this
type Talent struct {
Code string `json:"code" gorm:"type:varchar(10);not null"`
FirstName string `json:"firstName" example:"Ravi" gorm:"type:varchar(50)"`
LastName string `json:"lastName" example:"Sharma" gorm:"type:varchar(50)"`
Email string `json:"email" example:"john#doe.com" gorm:"type:varchar(100)"`
Contact string `json:"contact" example:"1234567890" gorm:"type:varchar(15)"`
AcademicYear *uint8 `json:"academicYear" example:"1" gorm:"type:tinyint(2)"`
Type *uint8 `json:"talentType" example:"4" gorm:"type:tinyint(2)"`
Resume *string `json:"resume" gorm:"type:varchar(200)"`
ExperienceInMonths *uint `json:"experienceInMonths"`
Image *string `json:"image" gorm:"type:varchar(200)"`
Gender *string `json:"gender" gorm:"type:varchar(50)"`
DateOfBirth *string `json:"dateOfBirth" gorm:"type:date"`
}
I want to update one field at a time, so I am sending only one field in json to the API as a PATCH http request and in backend(Golang) I am converting the json to struct where in only that field in json will have value in the struct... all other fields will be nil.
For example I am sending firstName, now when I convert it to struct only the firstName field is filled. Now I want to validate that field.. like firstName is a compulsary field so it will have two validations.. one for checking if its empty and one for the max number of characters.
Like wise all fields have some validations. Now how do I validate only that particular field. Having switch cases is what I had considered but is there any other optimal way to do this in golang??
import "gorm.io/gorm"
type Object struct {
gorm.Model
ObjectId string `gorm:"primary_key"`
ListItems []ListItem `gorm:"foreignKey:ObjectId;references:ObjectId"`
}
type ListItem struct {
gorm.Model
ObjectId string
Data string
}
I define two objects, then try to auto migrate following the guide
db.Migrator().CreateConstraint(&Object{}, "ListItems")
db.Migrator().CreateConstraint(&Object{}, "fk_object_list_items")
db.AutoMigrate(&Object{}, &ListItem{})
Fails with
ERROR: there is no unique constraint matching given keys for referenced table "blobber_ch
I can't find any examples for this. I tried different permutations of everything.
I suspect the foreign key in the migration does not match the foreign key in the model.
You have two primary_key for Object struct as gorm.Model already have one:
ID uint `gorm:"primarykey"`
You have two otpions : not to use gorm.Model or get rid of ObjectId primary_key and clean references:ObjectId from gorm annotation.
type Object struct {
gorm.Model
ObjectId string
ListItems []ListItem `gorm:"foreignKey:ObjectId;"`
}
type ListItem struct {
gorm.Model
ObjectId string
Data string
}
db.Migrator().CreateConstraint(&Object{}, "ListItems")
db.Migrator().CreateConstraint(&Object{}, "fk_object_list_items")
db.AutoMigrate(&Object{}, &ListItem{})
I have these two structs which represent the same entities (one comes from a Json file and the other from a DB)
type DriverJson struct {
ID int `json:"id"`
Name string `json:"name"`
}
type DriverOrm struct {
ID int `orm:"column(id);auto"`
Name string `orm:"column(name);size(255);null"`
}
I want to merge them into one Driver struct, how do I merge the mapping notations (orm:, json:)?
Thank you
As mentioned in the documentation of reflect.StructTag, by convention the value of a tag string is a space-separated key:"value" pairs, so simply:
type DriverJson struct {
ID int `json:"id" orm:"column(id);auto"`
Name string `json:"name" orm:"column(name);size(255);null`
}
For details, see What are the use(s) for tags in Go?
I have a user struct that corresponds to an entity. How can I add a new property active and set the default value to true?
Can I also set the value of that property to true for all existing entities by some easy method?
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
Bonus questions: I don't quite understand the syntax in the struct. What do the three columns represent? What do the JSON strings have ``around them?
//You can't change declared type.
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//Instead you construct a new one embedding existent
type ActiveUser struct {
User
Active bool
}
//you instantiate type literally
user := User{1, "John"}
//and you can provide constructor for your type
func MakeUserActive(u User) ActiveUser {
auser := ActiveUser{u, true}
return auser
}
activeuser := MakeUserActive(user)
You can see it works https://play.golang.org/p/UU7RAn5RVK
You have to set the default value as true at the moment when you are passing the struct type to a variable, but this means you need to extend that struct with a new Active field.
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
Active bool
}
user := User{1, "John", true}
json:"id" means that you are mapping the json decoded object field to the field id in your struct type. Practically you are deserialize the json string into object fields which later you can map to their specific field inside the struct.
How do I define my structs to specify a multi-column unique index to Gorm in Go?
Such as:
type Something struct {
gorm.Model
First string `sql:"unique_index:unique_index_with_second"`
Second string `sql:"unique_index:unique_index_with_first"`
}
this is how you do it: You need to use the gorm struct tag and specify that the index is unique
type Something struct {
gorm.Model
First string `gorm:"index:idx_name,unique"`
Second string `gorm:"index:idx_name,unique"`
}
You can define same unique index for each column.
type Something struct {
gorm.Model
First string `sql:"unique_index:idx_first_second"`
Second string `sql:"unique_index:idx_first_second"`
}
for latest version of gorm (or for my case)
this works:
type Something struct {
gorm.Model
First string `gorm:"uniqueIndex:idx_first_second"`
Second string `gorm:"uniqueIndex:idx_first_second"`
}