2017-10-16 58 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