How to bind custom column in struct

Hi,

I have a struct as following:-

type Trackings struct {

ClientId   uint 
Timeslice  time.Time
UserId  uint

}

In the trackings table ClientId is not present.So after joining the tables I m getting the clientId in MySQL but when I am printing the data in golang clientId is always 0.So Please tell me how to bind that clientId with the struct?

Thanks in advance.

Hey @Nirmal_Singh,

If you can show the code that you are currently trying to use, it will be much easier to help you and I’d be more than happy to help with that info if I’m able to.

Hi @radovskyb following is the sample code -

var track []Trackings

err :=DB.Select(“client.id as clientId,tracking.user_id as userId,user.name as user_name,tracking.timeslice as time”).
Table(“client”).
Joins(“left join user on user.client_id=client.id”).
Joins(“left join tracking on traking.user_id=user.id”).
Where(“client.active=1”).
Find(&track).Error

if(err!=nil){

log.Println(err);
}

fmt.Println(track);

When I am running this query in MySQL, I am getting the clientId for every row but when I am printing the track,clientId is showing 0 for all clients.Please let me know how can I get the clientId?

Thanks.

Hey @Nirmal_Singh,

It’s still a bit difficult to help you since you haven’t really provided that much here, for example, what ORM are you using or what are the 2 schemas for the tables, but either way, I’m going to take a guess here.

Try using this for your Trackings struct with the following struct tags added and let me know if anything changes:

type Trackings struct {
	ClientId  uint      `db:"clientId"`
	Timeslice time.Time `db:"time"`
	UserId    uint      `db:"userId"`
}

Also it would be helpful if you could paste an example of what is returned when running the code directly with MySQL.

Hi @radovskyb I am using Gorm for that.

What was the result with using the above for the Trackings struct?

If there was no change, try this too and let me know the result:

type Trackings struct {
	ClientId  uint      `db:"client_id"`
	Timeslice time.Time `db:"timeslice"`
	UserId    uint      `db:"user_id"`
}

ok I will try it and let you know if it works.Thanks.

I will point out, you did also misspell some things in your query I believe which could be causing you issues, for example you wrote this:

Joins("left join tracking on traking.user_id=user.id") <- misspelled tracking

Where I believe you probably meant this:

Joins("left join tracking on tracking.user_id=user.id")

@radovskyb thank you so much.It worked for me.

No problem, glad to help :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.