Android Firestore-添加对象数组
我正在使用Troble将对象数组(表)添加到对象数组(餐厅)。我的意思是,我有以下Firestore结构:Android Firestore-添加对象数组,android,firebase,flutter,Android,Firebase,Flutter,我正在使用Troble将对象数组(表)添加到对象数组(餐厅)。我的意思是,我有以下Firestore结构: ... (other data) restaurants: [ 0: { name: name_0 ... tables: [ 0: { no_chairs: 5, ... }, ] }, ... ] 我知道如何向餐馆添加新对象,但如果表列表包含任何数据,我在添加新餐馆时遇到问题 我的代码: v
... (other data)
restaurants: [
0: {
name: name_0
...
tables: [
0: { no_chairs: 5, ... },
]
},
...
]
我知道如何向餐馆添加新对象,但如果表列表包含任何数据,我在添加新餐馆时遇到问题
我的代码:
var collection = firestore.collection('usersData')
.doc(this.currentUser.uid).collection('buisness').doc('restaurants');
collection.update({
'restaurants': FieldValue.arrayUnion([restaurant.toJson()]),
}).then( ... // reaction based on api answer
高级餐厅:
映射到JSON()=>{
“名称”:名称,
...
“tables”:tables!=null?[tables]:[],//我想我应该修改这一行
};
类别表:
映射到JSON()=>{//或此方法/使用其他方法
“没有椅子”:没有椅子,
...
};
有什么简单的方法吗?最好不要修改firestore文件结构,但如果有必要,我愿意这样做
额外问题:
如何修改表列表中的对象?例如,我想将上面的代码中的no_chairs更改为7,下面的行有一个问题:
“表格”:表格=无效的[附表]:[],
这部分[tables]
表示将列表tables
作为外部列表的一个元素
举例说明,如果表格如下所示:
List tables=[1,2,3];
那么,[tables]
是这样的:
[[1,2,3]]
解决方案:
您可以直接使用tables
变量,因为您正在发送列表
在发送表格
对象之前,需要将其转换为当前存在的表格模型
列表中的地图列表(根据下面的注释)
因此,您可以将代码修改为:
“表”:表!=无效的tables.map((TableModel table)=>table.toJson()).toList():[],
额外问题:如何修改表列表中的对象?比如我
想把没有椅子换成7张吗
解决方案:
您必须获得餐厅的实际列表,并修改所需的确切表对象,然后将修改后的列表设置为Firestore
var collection=firestore.collection('usersData').doc(this.currentUser.uid).collection('buisness').doc('restaurants');
//获取餐厅列表
List restaurantList=((wait collection.get()).data()).map((dynamic restaurantJson)=>Restaurant.fromJson(restaurantJson)).toList();
设置椅子的数量
//
restaurantList[restaurantIndex]。表[tableIndex]。无椅子=7//这假设no_chairs字段不是最终字段
//集合列表
集合.set({
“餐厅”:restaurantList.toJson()
})
Without[]我得到错误:无法添加餐厅:无效参数:“TableModel”的实例作为FirebaseOK的响应,我将对此进行更新并进行修复。@下一步,请查看更新的答案。效果很好。你能帮我提个额外的问题吗编辑值?当然可以。我很快会更新我的答案。
class Restaurant:
Map<String, dynamic> toJson() => {
'name': name,
...
'tables': tables!=null? [tables] : [], // I think that I should modify this line
};
class Table:
Map<String, dynamic> toJson()=> { // Or this method / use another
'no_chairs': no_chairs,
...
};