【问题标题】:Relational query on PFObjectPFObject 上的关系查询
【发布时间】:2016-12-12 03:26:31
【问题描述】:

我有一个PFObjectAccount,其中包含Users 的数组,它们是PFUserss 的子类。然后User 有一个NSDictonary 属性allowableApps,这是数组的NSDictionary,其中数组包含PFObjects。

所以作为一个结构:

帐户

var users:   [User]

指向....

用户

// Each key is an array of AllowApp
var allowableApps: NSMutableDictionary

指向...

AllowableApp

var appName: String
var appURL:  String
var isAllowed: Bool

我试图在单个查询中将所有这些关系提取到AllowableApp。我试过像这样使用.includeKey

accountQuery?.includeKey("users")
accountQuery?.includeKey("allowableApps")

这没有用。我也试过:

accountQuery?.includeKey("users.allowableApps.appName")
accountQuery?.includeKey("users.allowableApps.appURL")
accountQuery?.includeKey("users.allowableApps.isAllowed")

我尝试使用所有AllowableApp 对象填充UITableView,但出现此错误:

Key "appName" has no data.  Call fetchIfNeeded before getting its value.

据我所知,在尝试访问 appName 属性之前,我需要获取所有这些。 (我正在尝试设置cellForRowAtIndexPath)。


这是我的完整查询:

let currentUser = User.currentUser()
        let accountQuery = Account.query()

        accountQuery?.whereKey("primaryUser", equalTo: currentUser!)
        accountQuery?.includeKey("users.allowableApps")

        accountQuery?.getFirstObjectInBackgroundWithBlock({ (account, error) in

            if (error != nil) {
                completion(users: nil, error: error)
            }
            else {
                let users = (account as? Account)!.users
                completion(users: users, error: nil)
            }
        })

我现在的想法是循环遍历viewDidAppear 中的所有AllowableApp 对象,调用fetchInBackgroundWithBlock。然后,一旦它们全部加载完毕,我就会重新加载表数据。

这看起来真的很混乱,而且是一个常见问题。有没有更优雅的解决方案,我只是没有看到?

【问题讨论】:

    标签: swift parse-platform pfobject


    【解决方案1】:

    据我了解,您的结构如下:

    • 帐户
      • 用户(用户数组)
        • AllowsableApps(AllowApps 数组)

    首先将 NSMutableDictionary 更改为 Array。 NSMutableDictionary 是一个键值对,在解析中你应该创建一个字段。所以你可以使用 Array of AllowApps,它会产生同样的效果。

    为了获取每个帐户中的所有帐户和用户以及每个用户允许的应用程序,您需要构建以下查询:

        // You can do it with sub classing if you want
        let query = PFQuery(className: "Account")
        query.includeKey("users.allowableApps")
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in
        }
    

    现在为您的用户数组。如果您的用户数组是需要登录应用程序的用户,最好从 PFUser 而不是从 PFObject 继承,因为 PFUser 包含所有逻辑在您的应用中处理用户。

    【讨论】:

    • 您好,感谢您的回复!我的结构更多 Account -> Users -> AllowableApps 如果这有意义的话。另外,我使用的是NSMutableDictionary,因为它们的键是我表中的部分标题视图。我想我理论上可以有一个AppCategory,这是一个PFObject,它有一个AllowableApps 的数组,但它看起来很健壮,只需要一个类别名称。
    • 嗨,是的,允许的应用程序应该在用户之下,我想我的缩进现在运行良好:)(我会更新我的答案)。无论如何,请尝试根据答案更改您的代码,因为我指的是与您相同的结构..
    • 我已更新我的问题以获取我正在运行的完整查询。当我尝试您建议的代码时,我收到错误 can only include pointer fields??
    • 这很奇怪...您是否在对象上创建了一些 ACL?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-11-20
    • 2020-11-08
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多