我使用golang,使用sqlx,我试图在页面上显示以下输出:
app_monitor.name | app_domains.name
基本上,它根据userid检索所有monitor.name,并从其他表中获取domain_name。我无法从其他表中获取域名。监视器名称检索成功。我应该在模型,控制器或模板引擎中获取domain_name吗?
以下是我的数据库中的一些字段:
app_monitor: id, name, domain_id
user: id, domain_id
app_domains: id, name
我的模型片段:
type Monitor struct {
ID uint32 `db:"id"` // Don't use Id, use MonitorID() instead for consistency with MongoDB
Name string `db:"name"`
DID uint32 `db:"domain_id"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
Status uint8 `db:"status"`
}
func MonitorByUserID(userID string) ([]Monitor, error) {
var err error
var result []Monitor
switch database.ReadConfig().Type {
case database.TypeMySQL:
err = database.SQL.Select(&result, "SELECT app_monitor.id, app_monitor.name, app_monitor.status FROM app_monitor LEFT JOIN user ON app_monitor.domain_id = user.domain_id WHERE user.id = ?", userID)
default:
err = ErrCode
}
return result, standardizeError(err)
}
我的控制器
func MonitorReadGET(w http.ResponseWriter, r *http.Request) {
// Get session
sess := session.Instance(r)
userID := fmt.Sprintf("%s", sess.Values["id"])
monitors, err := model.MonitorByUserID(userID)
if err != nil {
log.Println(err)
monitors = []model.Monitor{}
}
// Display the view
v := view.New(r)
v.Name = "monitor/read"
v.Vars["first_name"] = sess.Values["first_name"]
v.Vars["monitors"] = monitors
v.Render(w)
}
最后我的模板
<table class="table table-striped table-hover">
<tr>
<th scope="col-9">Monitor</th>
<th scope="col-3">Action</th>
</tr>
{{range $n := .monitors}}
<tr>
<td>{{.Name.DomainName}}</td>
<td><a title="Edit Monitor" class="btn btn-warning" role="button" href="{{$.BaseURI}}monitor/update/{{.MonitorID}}">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit
</a>
<a title="Delete Monitor" class="btn btn-danger" role="button" href="{{$.BaseURI}}monitor/delete/{{.MonitorID}}">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete
</a>
</td>
</tr>
{{end}}
</table>
但它说
Template File Error: template: read.tmpl:27:47: executing "content" at <.Name.DomainName>: can't evaluate field DomainName in type string
我怎样才能做到这一点?
答案 0 :(得分:0)
模板中的直接问题是:
<td>{{.Name.DomainName}}</td>
名称定义为string
类型的Monitor
字段。作为字符串,它没有名为DomainName
的子字段。因此错误:
无法在字符串
中评估字段DomainName
另外,
database.SQL.Select(&result, "SELECT app_monitor.id, app_monitor.name, app_monitor.status FROM app_monitor LEFT JOIN user ON app_monitor.domain_id = user.domain_id WHERE user.id = ?", userID)
模型包中的语句不检索DomainName。您还需要选择需要渲染的其他模型字段。
适当更新SQL后,以下代码段应呈现所需的输出:
<td>{{.Name}}</td>
<td>{{.DomainName}}</td>