GoLang How to load nested objects using GORM - mysql

Hi let's say that I have 3 Structs in the following format
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"foreignKey:CompanyId"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"foreignKey:OwnerId"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
func (E Employee) GetAllEmployees() ([]Employee, error) {
Employees := []Employee
db.Preload("Company").Find(&Employees)
}
// -- -- There response will be like
[
{
id: 1
name: "codernadir"
company: {
id: 5
company_name: "Company"
owner: {
id 0
Name ""
Age 0
Email ""
}
}
}
]
here I'm getting Owner values with the default values.
the given examples are for describing what I'm trying to reach.
I need a way how to load the Owner struct with its values when I load the Employees?
any suggestions will be appreciated and thanks in advance

You can use the gorm:"embedded" tag:
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"embedded"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"embedded"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}

this is what I found as a solution to load the nested objects from embedded structs
db.Preload("Company").Preload("Company.Owner").Find(&Employees)

Related

How can I get result as struct? (gorm)

My Category Entity is
type Category struct {
CategorySeq uint `json:"categorySeq" gorm:"primaryKey; column:category_seq"`
CategoryName string `json:"categoryName" gorm:"column:category_name"`
CategoryParentSeq uint `json:"-" gorm:"column:category_parent_seq"`
CategoryLevel int `json:"-" gorm:"column:category_level"`
}
The result struct as I want get data as
type ProductCategory struct {
Category1 Category `json:"category1" gorm:"embedded"`
Category2 Category `json:"category2" gorm:"embedded"`
Category3 Category `json:"category3" gorm:"embedded"`
}
And my database data is
table : category
category_seq | category_nanme | category_parent_seq
1 first 0
2 second 1
3 third 2
table : product
product_seq | category_seq
1 1
The result I want unmarshal Json as
"category": {
"category1": {
"categorySeq": 0,
"categoryName": ""
},
"category2": {
"categorySeq": 0,
"categoryName": ""
},
"category3": {
"categorySeq": 0,
"categoryName": ""
}
},
But I don't know how to get category result considering with parent_seq
so I try to use sql query like this
First I tried to select result as this struct
type CategoryRes struct {
CategorySeq1 uint `json:"categorySeq1,omitempty" gorm:"-"`
CategoryName1 string `json:"categoryName1,omitempty" gorm:"-"`
CategorySeq2 uint `json:"categorySeq2,omitempty" gorm:"-"`
CategoryName2 string `json:"categoryName2,omitempty" gorm:"-"`
CategorySeq3 uint `json:"categorySeq3,omitempty" gorm:"-"`
CategoryName3 string `json:"categoryName3,omitempty" gorm:"-"`
}
and use this orm query to get result as CategoryRes struct
func GetProductCategory(productSeq uint) *products.CategoryRes {
categoryRes := new(products.CategoryRes)
err := orm.GetData().
Model(&products.Category{}).
Select(
`category.category_seq AS CategorySeq3, category.category_name AS CategoryName3,
c2.category_seq AS CategorySeq2, c2.category_name AS CategoryName2,
c3.category_seq AS CategorySeq1, c3.category_name AS CategoryName1`,
).
Joins("LEFT JOIN product p ON p.product_category = category.category_seq").
Joins("LEFT JOIN category c2 ON category.category_parent_seq = c2.category_seq").
Joins("LEFT JOIN category c3 ON c2.category_parent_seq = c3.category_seq").
Where("p.product_seq = ?", productSeq).
Find(&categoryRes).Error
print(categoryRes)
if err != nil {
print("error category")
}
return categoryRes
}
but it is not mapping any fields...
I don't know why
If you give me hint It will very helpful to me.

Prisma One-to-One update Parent or update Parent and Child

I have a Parent Child (One-To-One) Relationship like this:
model Account {
id Int #id #default(autoincrement())
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
billingAddress Address?
name String
##map("Accounts")
}
model Address {
id Int #id #default(autoincrement())
city String?
country String?
postalCode Int?
state String?
street String?
accountId Int #unique
account Account #relation(fields: [accountId], references: [id])
}
I want to be able to Update the Parent Record without the need of updating also the Child Record. Furthermore, it would be great, if I can update the Parent Record and the Child Record at the same time. Right now I am getting an Error when only trying to send the Data for the Parent Record.
Here are my DTOs to Create and Edit the Entities:
Create / Edit Account:
export class CreateAccountDto {
#IsString()
#IsOptional()
name: string;
#IsOptional()
billingAddress?: CreateAddressDto;
}
Create / Edit Addresss:
export class EditAddressDto {
#IsString()
#IsOptional()
city?: string;
#IsString()
#IsOptional()
country?: string;
#IsNumber()
#IsOptional()
postalCode?: number;
#IsString()
#IsOptional()
state?: string;
#IsString()
#IsOptional()
street?: string;
#IsInt()
#IsOptional()
accountId: number;
}
I'm creating and editing the Account like this:
async editAccount(accountId: number, dto: EditAccountDto) {
let account;
console.log({dto})
account = await this.prisma.account.update({
where: {
id: accountId
},
data: {
...dto,
billingAddress: {
update: {
...dto.billingAddress
}
}
},
include: {
billingAddress: true
}
});
console.log(account)
return account;
}
When i try to Edit the Account with the following Data
{
"name": "Test Account Create2",
"billingAddress": {
"id": 2,
"city": "Dortmund",
"state": "NRW",
"postalCode": 44442,
"country": "Germany",
"street": "Benninghofer Heide 63",
"accountId": 10000001
}
}
i am getting the following Error:
Unknown arg `accountId` in data.billingAddress.update.accountId for type AddressUncheckedUpdateWithoutAccountInput. Did you mean `country`? Available args:
type AddressUncheckedUpdateWithoutAccountInput {
id?: Int | IntFieldUpdateOperationsInput
city?: String | NullableStringFieldUpdateOperationsInput | Null
country?: String | NullableStringFieldUpdateOperationsInput | Null
latitude?: Decimal | NullableDecimalFieldUpdateOperationsInput | Null
longitude?: Decimal | NullableDecimalFieldUpdateOperationsInput | Null
postalCode?: Int | NullableIntFieldUpdateOperationsInput | Null
state?: String | NullableStringFieldUpdateOperationsInput | Null
street?: String | NullableStringFieldUpdateOperationsInput | Null
}
at Document.validate (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:29297:20)
at serializationFn (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31876:19)
at runInChildSpan (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:25100:12)
at PrismaService._executeRequest (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31883:31)
at consumer (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31810:23)
at C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31815:51
at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
at C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31815:29
at runInChildSpan (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:25100:12)
at PrismaService._request (C:\Users\Simon\IdeaProjects\crm-tool\crm-backend\node_modules\#prisma\client\runtime\index.js:31812:22)
The error says, you are not allowed to specify accountId when you are updating the address in this way. You can just remove it from your DTO and everything should be fine.

How to map enums to Bson&Json to store in mongoDB in Golang

I came up with a situation where my MongoDB has a field stored as a string and I need to ensure that field has only specific enum values.
Similarly, I should be getting requests with the same enums only and should be able to that struct variable everywhere as an enum.
type studentModel struct {
studentType enums.StudentType `bson:"studentType, omitempty" json:"studentType,omitempty"`
studentId int64 `bson:"studentId, omitempty" json:"studentId,omitempty"`
}
studentType Enum Values : PAID , UNPAID , INACTIVE
Your enum is of type string.
Your can declare it like this
package enums
type StudentType string
Your enums
const (
PAID enums.StudentType = "PAID"
UNPAID enums.StudentType = "UNPAID"
INACTIVE enums.StudentType = "INACTIVE"
)
type studentModel struct {
studentType enums.StudentType `bson:"studentType,omitempty" json:"studentType,omitempty"`
studentId int64 `bson:"studentId,omitempty" json:"studentId,omitempty"`
}

How to update values for all rows having null value | Prisma | Type script | MySQL

I have prisma schema like below
model t1 {
id Int #id #default(autoincrement())
title String
previousNodeId Int? #unique
}
and I wanted to update title of rows who have null values in previousNodeId
I have written query
await prisma.t1.update({
where: { previousNodeId: null },
data: {
title:"update title"
}
});
but I am not able to update it.
Getting error Type 'null' is not assignable to type 'number | undefined'.
The expected type comes from property 'previousNodeId' which is declared here on type 'T1WhereUniqueInput'
I am able to get all rows using findMany.
await prisma.t1.findMany({
where: { previousNodeId: null },
});
Result of findMany
[
{
id: 3,
title: 'demo t1 1',
previousNodeId: null
}
]

elm - updating a record within a record

What is the correct/best way to update a record within a record?
The following attempt:
type alias Model =
{ pageView : PageView
, landingPageModel : Dict
}
--update
update : Action -> Model -> Model
update action model =
case action of
ChangePage pView ->
{ model | pageView = pView }
PostCode pCode ->
let
lPModel =
model.landingPageModel
newlPModel =
{ lPModel | postCode = pCode }
in
{ model | landingPageModel = newlPModel }
gave this error:
The type annotation for `update` does not match its definition.
19│ update : Action -> Model -> Model
^^^^^^^^^^^^^^^^^^^^^^^^
The type annotation is saying:
Action
-> { ..., landingPageModel : Dict }
-> { ..., landingPageModel : Dict }
But I am inferring that the definition has this type:
Action
-> { ..., landingPageModel : { a | postCode : String } }
-> { ..., landingPageModel : { a | postCode : String } }
This is somewhat surprising - isn't a literal Dict update of type Dict?
I simply needed to expand the Model definition :
type alias Model =
{ pageView : PageView
, landingPageModel : { postCode : String }
}
Also, as per halfzebra's comment, Dict's have no relevance here - just records.