删除父记录时删除位于数组中的嵌套解析对象

Remove nested parse objects located in Array when removing parent record

我有一个自定义 class Invoice,其中包含一组自定义 classes InvoiceItems。

当我删除 Invoice 时,我想删除与其关联的所有记录。当前,当我删除 Invoice 时,发票项目仍列在数据库中。

我想当您删除父记录时,它应该删除嵌套项,因为我使用的是数组而不是关系或指针。

func removeInvoice(with invoice: Invoice, completion: @escaping (Result<Bool, NSError>) -> ()) {
        
        guard let invoiceObjectId = invoice.getPFInvoice()?.objectId else {
            let error = NSError(domain: "OURTEAM", code: 0, userInfo: [NSLocalizedDescriptionKey: "Remove invoice failure"])
            completion(.failure(error))
            return
        }
        
        let query = PFQuery(className: "Invoice")
        query.whereKey("objectId", equalTo: invoiceObjectId)
        
        query.findObjectsInBackground { (objects, error) in
            
            if let unwrappedError = error as NSError? {
                completion(.failure(unwrappedError))
            }
            
            if let unwrappedObjects = objects {
                
                for object in unwrappedObjects {
                    object.deleteEventually()
                }
                
                completion(.success(true))
            }
        }
    }

您可以创建 afterDelete 触发器来删除子项:

Parse.Cloud.afterDelete('Invoice', ({ object }) => {
  return Parse.Object.destroyAll(object.get('arrayField'));
});