2017-10-16 60 views
0

我无法在我的桌子上增加行数
我使用了revel框架,并尝试使简单的crud。Go lang增量编号

问题是:“如何使用Golang显示增量数?”。

这是我的控制器的代码book.go
该控制器,显示从PostgreSQL数据库的数据。

func allBooks() ([]models.Book, error) { 
    //Retrieve 
    books := []models.Book{} 

    rows, err := db.Query("SELECT id, name, author, pages, publication_date FROM books order by id") 
    defer rows.Close() 
    if err == nil { 
     for rows.Next() { 
      var id int 
      var name string 
      var author string 
      var pages int 
      var publicationDate pq.NullTime 

      err = rows.Scan(&id, &name, &author, &pages, &publicationDate) 
      if err == nil { 
       currentBook := models.Book{ID: id, Name: name, Author: author, Pages: pages} 
       if publicationDate.Valid { 
        currentBook.PublicationDate = publicationDate.Time 
       } 

       books = append(books, currentBook) 
      } else { 
       return books, err 
      } 

     } 
    } else { 
     return books, err 
    } 
    return books, err 
} 

而且这个网站上我的看法的index.html

<table class="table table-striped"> 
    <thead> 
    <tr> 
     <th>No</th> 
     <th>ID</th> 
     <th>Name</th> 
     <th>Author</th> 
     <th>Pages</th> 
     <th>Publication Date</th> 
     <th>Action</th> 
    </tr> 
    </thead> 
    <tbody> 

    {{range .books}} 
    <tr> 
     <td>{{.Nomor}}</td> 
     <td>{{.ID}}</td> 
     <td>{{.Name}}</td> 
     <td>{{.Author}}</td> 
     <td>{{.Pages}}</td> 
     <td>{{.PublicationDateStr}}</td> 
    </tr> 
    {{end}} 
    <tr> 
     <td></td> 
     <td></td> 
     <td></td> 
     <td></td> 
     <td></td> 
     <td><a href="book.html" class="btn btn-primary">New book</a></td> 
    </tr> 
    </tbody> 
</table> 

希望造成这样

 
|No.|ID |Name |Author | Pages | Publication Date | 
|1 |2 |Jack |Holly | 255 | 2017-10-15  | 
|2 |4 |hans |Holly | 255 | 2017-10-15  | 
|3 |6 |Juri |Holly | 255 | 2017-10-15  | 
|4 |7 |Hank |Holly | 255 | 2017-10-15  | 

但我得到的是

 
|No.|ID |Name |Author | Pages | Publication Date | 
|0 |2 |Jack |Holly | 255 | 2017-10-15  | 
|0 |4 |hans |Holly | 255 | 2017-10-15  | 
|0 |6 |Juri |Holly | 255 | 2017-10-15  | 
|0 |7 |Hank |Holly | 255 | 2017-10-15  | 
+1

它现在是什么样子? –

+0

你可以使用'row_number()(按ID排序)'生成该号码 –

+0

@EugeneLisitsky问题是更新。 –

回答

0

我不要 请参阅任何地方的Nomor资源。

你应该保持一个计数器,并完成类似

... 
currentBook := models.Book{Nomor: count, ID: id, Name: name, Author: author, Pages: pages} 
count = count + 1 
... 
0

你可以尝试assinging切片指数的值给一个变量,并尝试打印,像

{{range $index, _ := .books}} 

和使用索引而不是Nomor