Firebase 颤振/飞镖/火基-更新的嵌套贴图值
我正在尝试记录我的用户在我的应用程序中购买了哪张票。我正在使用firebase存储有关我的用户和赠品的数据。购买完成后,我会尝试更新相关赠品,并使用用户id将每张票分配给用户 首先,我不确定我的数据模式是否最适合我正在尝试实现的目标,因为我对编辑的建议非常开放,因为我对颤振世界还很陌生 其次,以下是我的数据当前的结构: 下面是我如何构建代码的。以下是我的SingleBasketItem型号:Firebase 颤振/飞镖/火基-更新的嵌套贴图值,firebase,flutter,dictionary,dart,google-cloud-firestore,Firebase,Flutter,Dictionary,Dart,Google Cloud Firestore,我正在尝试记录我的用户在我的应用程序中购买了哪张票。我正在使用firebase存储有关我的用户和赠品的数据。购买完成后,我会尝试更新相关赠品,并使用用户id将每张票分配给用户 首先,我不确定我的数据模式是否最适合我正在尝试实现的目标,因为我对编辑的建议非常开放,因为我对颤振世界还很陌生 其次,以下是我的数据当前的结构: 下面是我如何构建代码的。以下是我的SingleBasketItem型号: class SingleBasketItem { final String id; fina
class SingleBasketItem {
final String id;
final String uid;
final OurGiveAways giveaway;
final int ticketNumber;
SingleBasketItem(this.id, this.uid, this.giveaway, this.ticketNumber);
}
这是我的购物篮模型,我在我的购物篮页面上添加了一个提升按钮,点击该按钮后,将执行placeOrder()函数:
class ShoppingBasket extends ChangeNotifier {
Map<String, SingleBasketItem> _items = {};
Map<String, SingleBasketItem> get items {
return {..._items};
}
void addItem(String id, String uid, OurGiveAways giveaway, int ticketNumber) {
_items.putIfAbsent(
id,
() => SingleBasketItem(id, uid, giveaway, ticketNumber),
);
notifyListeners();
}
void placeOrder(BuildContext context, OurUser user) {
for (var i = 0; i < _items.length; i++) {
FirebaseFirestore.instance
.collection('giveaways')
.doc(_items.values.toList()[i].giveaway.giveawayId)
.update(
{
'individual_ticket_sales'[_items.values.toList()[i].ticketNumber]:
user.uid,
},
);
}
}
}
class ShoppingBasket扩展ChangeNotifier{
映射_项={};
映射获取项目{
返回{…\u items};
}
void addItem(字符串id、字符串uid、我们的赠品赠品、int ticketNumber){
_项目。putIfAbsent(
身份证件
()=>SingleBasketItem(id、uid、赠品、票号),
);
notifyListeners();
}
void placeOrder(BuildContext上下文,OurUser){
对于(变量i=0;i<\u items.length;i++){
FirebaseFirestore.instance
.收藏(“赠品”)
.doc(_items.values.toList()[i].giveaway.giveawayId)
.更新(
{
“个人门票销售”[\u items.values.toList()[i].ticketNumber]:
user.uid,
},
);
}
}
}
以下是结果的图像:
通过分析结果,我的代码似乎正在创建一个新字段,其标题为个人售票的第一个索引字符(“n”,因为我买了票1),我如何将嵌套的“1”(或我选择的任何票)设置为我的用户id,而不是创建一个新字段?谢谢。我建议您重构数据库结构,因为您遇到的第一个问题是,
firestore
目前不支持为数组字段值更新特定索引。你可以得到更多的信息
您可以获得整个值个人\u ticket\u sales
更新它并将其作为一个整体再次保存,但您会遇到多个用户希望在几乎相同的时间更新相同的值,并且其中一个更改丢失的问题,这只是时间问题。由于对象的大小和潜在的多次更改,即使事务的使用也不是100%安全的
您是否可以将每个ticketId
作为firestore文档
存储在firestore集合
中,如下所示:
FirebaseFirestore.instance
.收藏(“赠品”)
.doc(_items.values.toList()[i].giveaway.giveawayId)
.collection(“个人票销售”)
.doc(i)
.update(user.uid);