type User struct {
Id uint64 `json:"id" gorm:"primaryKey"`
FullName string `json:"full_name"`
Moniker string `json:"moniker"`
Contact string `json:"contact"`
Email string `json:"email"`
}
type UserAccount struct {
Id uint64 `gorm:"primaryKey"`
CompanyRank string `json:"company_rank"`
SystemLevel string `json:"system_level"`
Department string `json:"department"`
UserRefer int `json:"fkuser_id"`
User User `gorm:"foreignKey:UserRefer"`
}
This the method that gets list of all records in UserAccount table in database
func (h handler) GetUserAccounts(ctx *gin.Context) {
userAccounts := []model.UserAccount{}
var users []model.User
links := model.BodyNLinks()
links.Title = "Roles List"
links.Heading = "Roles List"
if result := h.DB.Find(&userAccounts); result.Error != nil {
ctx.AbortWithError(http.StatusNotFound, result.Error)
return
}
for _, v := range userAccounts {
user := model.User{}
if result := h.DB.Find(&user, v.UserRefer); result.Error != nil {
ctx.AbortWithError(http.StatusNotFound, result.Error)
return
}
users = append(users, user)
}
ctx.HTML(200, "useraccount/list.html", gin.H{
"userAccounts": userAccounts,
"users": users,
"link": links,
})
}
The html page used to display records from user_accounts database
{{ define "useraccount/list.html" }}
{{ template "01Temps/header.html" . }}
<ul>
{{range $xi := .users}}
<li>{{$xi.FullName}} {{$xi.Contact}}</li>
{{end}}
</ul> </br>
<table na border="1">
<tr align="right">
<th>USER</th>
<th>FullName</th>
<th>Email</th>
<th>Department</th>
<th>Level</th>
<th>Role</th>
<th>Action</th>
</tr>
<tbody id="myTbl">
{{range $xi := .userAccounts}}
<tr align="left">
<td>
<a href="/user/getrecord/{{$xi.UserRefer}}"
onclick=" return confirm('Redirect to USER:{{$xi.UserRefer}} ?')">
USR:{{$xi.UserRefer}}</a>
</td>
{{range $xu := .users}}
<td>{{$xu.FullName}}</td>
<td>{{$xu.Email}}</td>
{{end}}
<td>{{$xi.Department}}</td>
<td>{{$xi.SystemLevel}}</td>
<td>{{$xi.CompanyRank}}</td>
<td><a href="/useraccount/updaterecord/{{$xi.Id}}"
onclick="return confirm('Update USER:{{$xi.UserRefer}} ?')">Update</a>
<label>||</label>
<a href="/useraccount/deleterecord/{{$xi.Id}}"
onclick="return confirm('Delete USER:{{$xi.UserRefer}} ?')">Del</a>
<label>||</label>
<a href="/useraccount/getrecord/{{$xi.Id}}"
onclick="return confirm('Display USER:{{$xi.UserRefer}} ?')">Display</a>
</td>
</tr>
{{end}}
</tbody>
</table>
</br>
{{ template "01Temps/footer.html" . }}
{{end}}
Why can’t I display users and userAccounts data from controller into same template table rows.
In UsertAccount struct, if I was to
UserRefer int json:"fkuser_id"
UserFullNameRefer string json:"fkuser_full_name"
User User gorm:"foreignKey:UserRefer"
How would I add UserFullNameRefer as a foreign column from User struct