2016-10-02 324 views
0

导致更新特定对象我在火力地堡DB的结构如下:斯威夫特火力地堡:从火力地堡查询

Firebase JSON

我期待与特定mealID更新read属性true所有对象。我曾尝试这样的:

if let selectedIndexPath = tableView.indexPathForSelectedRow { 
       meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false 
       let mealId = mealIds[(selectedIndexPath as NSIndexPath).row] 
       let notificationsRef = ref.child("notifications") 
       //get all notifications with this mealId 
       var mealNotifications = notificationsRef.queryOrdered(byChild: "mealId").queryEqual(toValue: mealId) 
       //notificationRef.updateChildValues(["read":true]) 
      } 

该查询输出正确的通知对象,我只是不知道如何(使用mealNotifications)更新这些特定对象。有任何想法吗?

EDIT

我已经加入一个观察事件,但是我没有在输出接收到任何对象(我期待一个单输出)。我相信这是因为我正在查看通知ID级别,而不是mealID级别。我怎样才能纠正这个查询?

if let selectedIndexPath = tableView.indexPathForSelectedRow { 
       meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false 
       let mealId = mealIds[(selectedIndexPath as NSIndexPath).row] 
       let notificationsRef = ref.child("notifications") 
       //get all notifications with this mealId 
       var mealNotifications = notificationsRef.queryOrdered(byChild: "mealId").queryEqual(toValue: mealId).observe(.value, with: {snapshot in 
        print("MEALS:",snapshot) 
        }) 
       //notificationRef.updateChildValues(["read":true]) 
      } 
+1

你需要附加一个观察者,环比儿童和调用'child.ref.updateChildValues()'。请参阅http://stackoverflow.com/questions/36821000/how-to-update-firebase-query –

+0

谢谢。看来我的查询是不正确的,因为我正在尝试查看notificationsRef以下的级别。有没有指定byChild参数应该降低的方法? – benjanisa

+0

我在 – benjanisa

回答

0

以下工作:

if let selectedIndexPath = tableView.indexPathForSelectedRow { 
       meals[(selectedIndexPath as NSIndexPath).row].unreadNotification=false 
       let mealId = mealIds[(selectedIndexPath as NSIndexPath).row] 
       let notificationsRef = ref.child("notifications") 
       //get all notifications with this mealId 
       var mealNotifications = notificationsRef.queryOrdered(byChild: "mealID").queryEqual(toValue: mealId).observe(.value, with: {snapshot in 
        let enumerator = snapshot.children 
        while let rest = enumerator.nextObject() as? FIRDataSnapshot { 
         notificationsRef.child(rest.key).child("read").setValue(true) 
         } 
         }) 
        tableView.reloadRows(at: [selectedIndexPath], with: .none) 
       }