# Beego DB primary key and Relationship Explore
## One to One
Means a relationship between to structs where one instance of one struct can be related to one instance of the other struct.
Suppose, there is a Facebook user. The user can have only one profile as that user. So if User and Profile are two models then their relationship is one-to-one.
```go=
type User struct {
UserId int
Name string
Age int
Profile *Profile `orm:"rel(one)"`
}
type Profile struct {
Id int // primary key
Education string
Workplace string
ContactNumber string
User *User `orm:"reverse(one)"` // foreign key
}
```
## One to many
Example, a facebook user can have multiple posts. If user and post are two structs then user has one to many relationship with post. To integret this with orm following steps can be performed.
```go=
type User struct {
UserId int
Name string
Age int
Posts []*Post `orm:"reverse(many)"`
}
type Post struct {
Id int // primary key
Heading string
Topic string
User *User `orm:"rel(fk)"` // foreign key
}
```
## Many to many
Again coming to facebook, a post can have multiple tags and same tag can be usd in multiple posts. In database world this relationship is called many to many.
```go=
type Tag struct {
Id int
Name string
Posts []*Post `orm:"reverse(many)"`
}
type Post struct {
Id int // primary key
Heading string
Topic string
Tags []*Tag `orm:"rel(m2m)"` // foreign key
}
```
**Could not verify many to many relationship using*
## Setting Primary key
By default when a table is created, Beego creates an Id field as primary key. However, we can set a primary key of our choice as well while declaring the struct for the model.
*/models/user.go*
```go=
type User struct {
Id int
Name string
Age int
}
```
When the model is created for above struct, Beego Orm takes `Id` as primary key.
Changed */models/user.go*
```go=
type User struct {
Id int
UserId string `orm:"pk"`
Name string
Age int
}
// demo function to generate the UserId as it cannot be incremental here
func generateUserId(Age int, name string) string {
return strconv.ItoA(Age)+"/"+name
}
```
### Links
1. [Key setting](https://blog.csdn.net/Charles_Thanks/article/details/80502829)
2. [Beego Documentation](https://beego.me/docs/mvc/model/models.md)
3. [Primary Key Value related](https://ddcode.net/2019/04/14/beegos-orm-gives-the-primary-key-value-every-updatedeleteread/)
4. [Primary key field using Beego](https://developpaper.com/question/encounter-need-a-primary-key-field-when-using-beego/)