如何使用 Hive 在 Dart 中按值(而不是按索引)read/update/delete?
How to read/update/delete by value(not by index) in Dart using Hive?
样本
deleteItem(int index) {
final box = Hive.box<Delivery>("deliveries");
box.deleteAt(index);
}
我想将索引参数更改为我的对象的 ID),就像这样
deleteItem(int id) {
final box = Hive.box<Delivery>("deliveries");
// box.deleteAt(index);
// box delete by id here
}
这是我的 TypeAdapter class:
@HiveType(typeId: 0)
class Delivery {
@HiveField(0)
final int id;
Delivery(this.id);
}
将键值数据库视为具有单词及其定义的常规好旧词汇表。它允许您使用给定的词非常快速地找到定义(假设您正在寻找词 elephant
)。但是,如果您想找到定义为 An animal with big ears.
的条目,则需要更长的时间。
经过大量简化,这就是键值数据库的工作方式。 当您使用索引进行查询时,它们很快。
所以如果你想使用id查询,我建议使用索引本身的id。
例如:
Indexes:
delivery-001
delivery-002
...
或者,如果您还想执行一些其他更复杂的查询,我建议您使用 sqflite 的常规 SQLite 数据库。
如另一个答案所述,这是不可能的,除非您搜索每个项目并逐个比较它们的 ID 。根据您盒子中物品的数量,这可能需要更长时间或根本无关紧要。
这种未优化方式的一个示例是:
deleteItem(int id) {
final box = Hive.box<Delivery>("deliveries");
final Map<dynamic, Delivery> deliveriesMap = box.toMap();
dynamic desiredKey;
deliveriesMap.forEach((key, value){
if (value.id == id)
desiredKey = key;
});
box.delete(desiredKey);
}
此代码的作用是使用 toMap() method. With a map in hands, we iterate through every entry on it, checking which one has the specific ID and keep record of that. After that we just delete the found key using the delete() method. You can read more about iterating through Maps .
将方框 class 变成地图
请记住,这只是一个示例。如果您尝试使用它,您可能需要检查是否确实存在具有您正在搜索的 ID 的项目。如果是这种情况,您还需要在您的 Box 中检查具有相同 ID 的多个值。
样本
deleteItem(int index) {
final box = Hive.box<Delivery>("deliveries");
box.deleteAt(index);
}
我想将索引参数更改为我的对象的 ID),就像这样
deleteItem(int id) {
final box = Hive.box<Delivery>("deliveries");
// box.deleteAt(index);
// box delete by id here
}
这是我的 TypeAdapter class:
@HiveType(typeId: 0)
class Delivery {
@HiveField(0)
final int id;
Delivery(this.id);
}
将键值数据库视为具有单词及其定义的常规好旧词汇表。它允许您使用给定的词非常快速地找到定义(假设您正在寻找词 elephant
)。但是,如果您想找到定义为 An animal with big ears.
的条目,则需要更长的时间。
经过大量简化,这就是键值数据库的工作方式。 当您使用索引进行查询时,它们很快。
所以如果你想使用id查询,我建议使用索引本身的id。
例如:
Indexes:
delivery-001
delivery-002
...
或者,如果您还想执行一些其他更复杂的查询,我建议您使用 sqflite 的常规 SQLite 数据库。
如另一个答案所述,这是不可能的,除非您搜索每个项目并逐个比较它们的 ID 。根据您盒子中物品的数量,这可能需要更长时间或根本无关紧要。
这种未优化方式的一个示例是:
deleteItem(int id) {
final box = Hive.box<Delivery>("deliveries");
final Map<dynamic, Delivery> deliveriesMap = box.toMap();
dynamic desiredKey;
deliveriesMap.forEach((key, value){
if (value.id == id)
desiredKey = key;
});
box.delete(desiredKey);
}
此代码的作用是使用 toMap() method. With a map in hands, we iterate through every entry on it, checking which one has the specific ID and keep record of that. After that we just delete the found key using the delete() method. You can read more about iterating through Maps
请记住,这只是一个示例。如果您尝试使用它,您可能需要检查是否确实存在具有您正在搜索的 ID 的项目。如果是这种情况,您还需要在您的 Box 中检查具有相同 ID 的多个值。