在Bolt中找一个。

huangapple go评论95阅读模式
英文:

Find one in Bolt

问题

我有一个使用Golang编写的项目,使用Bolt作为我的数据库。我发现并开始使用这个项目来处理数据库的连接和操作。我目前的问题是,我无法通过一个字段进行搜索并获得一个结果。

我在Golang中的结构定义如下:

type Component struct {
    ID       int      `storm:"increment"`
    Name     string   `storm:"id,unique"` // 主键
    Cars     []string `storm:"index"`     // 这个字段将被索引
    Houses   []string `storm:"index"`     // 这个字段将被索引
    Pets     []string `storm:"index"`     // 这个字段将被索引
    Children []string `storm:"index"`     // 这个字段将被索引
    Level    int
}

首先,我知道在一个字段中同时有一个ID字段和一个带有标签id的Name字段是奇怪的,问题是我希望将名称作为ID,可能也作为键。我进行了一些插入操作,一切正常,我甚至成功检索到了所有的值。
现在,我想通过名称获取一个元素,我有以下代码:

name := "someComponent"
var component models.Component
err := db.One("Name", name, &component)

但是它返回了not found,但我知道一个组件是以那个名称存储的。另一方面,如果我使用Find进行搜索,我可以得到该元素,但该命令用于返回多个结果,而我只想要一个结果,我有以下代码:

var components []models.Component
err := db.Find("Name", name, &components)
英文:

I have a Golang project and I am using Bolt as my Database. I found and started to use This project to handle the connection and operations over the database. My current problem is that I cannot make a search by one field and get one result.

My struct definition in Golang is:

type Component struct {
	ID          int      `storm:"increment"`
	Name        string   `storm:"id,unique"` // primary key
	Cars        []string `storm:"index"`  // this field will be indexed
	Houses      []string `storm:"index"`  // this field will be indexed
	Pets        []string `storm:"index"`  // this field will be indexed
	Children    []string `storm:"index"`  // this field will be indexed
	Level       int
}

At first, I know is strange to have one field ID and a field Name with the tag id, the thing is that I want the name as the id and possibly as the key. I made some inserts and everything is ok, I even retrieved all the values and it worked perfectly.
Now, I want to get one element by his name, I have this:

name := "someComponent"
var component models.Component
err := db.One("Name", name, &component)

But it returns not found but I know that a component is stored with that name. In other hand, if I make the search with Find I get the element, but that command is to return many results, and I want only one, I have this:

var components []models.Component
err := db.Find("Name", name, &components)

答案1

得分: 2

从我的评论中起草答案。

根据库的代码库,即使Name被定义为主键,ID也会妨碍你。

如果你想保持Name作为主键,你可以请移除结构体Component中的ID字段,然后尝试使用db.One方法。

英文:

Drafting answer from my comment.

Per library codebase, ID is getting in your way even though Name is defined as primary key.

If you would like to keep Name as primary key, can you please remove the field ID from struct Component and then try method db.One.

huangapple
  • 本文由 发表于 2017年7月12日 07:07:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/45045839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定