Swift5.1+Realm3.19.1反向链接查询报错:查询禁用却检测到反向关联
Let's break down what's happening here and how to fix it:
The Root Cause
Realm 3.x (including your 3.19.1 version) does not support querying directly over LinkingObjects—this is a limitation of older Realm versions, which is probably why you couldn't find clear documentation about it. When you tried to filter Todo objects using ANY user.uid, you're attempting to query through the backlink defined by LinkingObjects, which is disabled in Realm 3.x.
The Best Fix (No Version Upgrade Needed)
Since your data structure already has User containing a List<Todo>, you can completely avoid the backlink query by reversing your approach: first fetch the target User, then access their todos directly. This is also more efficient than querying from the Todo side.
Here's how to adjust your code:
// First find the User with the target uid if let targetUser = realm.objects(User.self).filter("uid == %@", uid).first { // Access the user's todos directly—no backlink query needed! let userTodos = targetUser.todos // Work with userTodos here }
Alternative: Upgrade Realm (If You Need Todo-Side Queries)
If you absolutely need to query from the Todo model side (for specific use cases), you'll need to upgrade Realm to version 4.0 or later. Realm introduced support for querying over LinkingObjects starting in v4.0, which would make your original filter code work as expected. Just keep in mind to test for compatibility with your project's other dependencies when upgrading.
Quick Check on Your Model Definitions
Your model setup is correct:
Userhas aList<Todo>to track their tasksTodousesLinkingObjectsto create the inverse relationship toUser
The only issue is the version limitation preventing the backlink-based query.
内容的提问来源于stack exchange,提问作者zeeshan

