微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对于 ToOne 和 ToMany

如何解决对于 ToOne 和 ToMany

最近从 1.0.0 更新到 1.1.1,我的关系代码停止工作,我不确定我到底错过了什么,但直到项目查询似乎正常工作为止。

这就是我所拥有的,我真的可以使用一些帮助来弄清楚我错过了什么

店铺创建:

  void initializeUserInventory() async {
    await getApplicationDocumentsDirectory().then((dir) {
      try {
        _quickSaveStore =
            Store(getobjectBoxModel(),directory: dir.path + '/quickSaveItems');
        _quickactionStore = Store(getobjectBoxModel(),directory: dir.path + '/quickSaveActions');
        _categorizedSaveStore = Store(getobjectBoxModel(),directory: dir.path + '/categorizedSaveItems');
        _itemCategoryStore = Store(getobjectBoxModel(),directory: dir.path + '/categorizedSaveCategories');
        _itemTagsstore = Store(getobjectBoxModel(),directory: dir.path + '/categorizedSaveTags');
      } catch (e) {
        print(e.toString());
      }
    }).whenComplete(() {
      // Must initialize everything else after completion of store initialization!
      _userQuickSaveBox = Box<InitialItem>(_quickSaveStore!);
      _quickactionSaveBox = Box<QuickSaveAction>(_quickactionStore!);
      _categorizedSaveBox = Box<InitialItem>(_categorizedSaveStore!);
      _itemCategoryBox = Box<ItemCategory>(_itemCategoryStore!);
      _itemTagsBox = Box<ItemTag>(_itemTagsstore!);
    });
  }

这里是实体文件: 初始项:

part 'initial_item.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class InitialItem {
  String? itemName;
  String? inc;
  DateTime cacheTime;
  DateTime? saveTime;


  @Id(assignable: true)
  int id;

  //#region Category
  //
  // Functions that are utilized for Saving the item by Category
  //
  /// Holds the count of how many items the vehicle/WO needs
  int? quantity;

  /// Any comments the user has added to the item
  String? userComment;

  /// Category that the item belongs too
  final itemCategory = ToOne<ItemCategory>();

  /// Allows adding a tag to the saved item
  final tags = ToMany<ItemTag>();

  //#endregion


  InitialItem(
      {this.id = 0,this.itemName,this.inc,this.quantity = 1,DateTime? cacheTime,DateTime? saveTime,this.userComment = '',})
      : cacheTime = cacheTime ?? DateTime.Now(),saveTime = cacheTime ?? DateTime.Now();
}

项目类别:

part 'item_category.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class ItemCategory {
  int id;
  String? categoryUid;
  String? userUid;
  String? categoryName;
  String? categoryComment;

  @Backlink()
  final items = ToMany<InitialItem>();

  ItemCategory(
      {this.id = 0,this.userUid,this.categoryName,this.categoryUid,this.categoryComment});
}

项目标签

part 'item_tag.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class ItemTag {
  int id;
  String? name;

  /// Only used for FilterChip display,not saved in any database
  @Transient()
  bool isSelected;
  String? uid;

  ItemTag({this.id = 0,this.name,this.isSelected = false,this.uid});
}

标签和类别已经由用户创建并保存在他们的框中。一个项目被传递到视图中,用户可以为项目添加标签,并且可以选择一个类别来保存项目。

  /// Attaches the tags that the user selected to the item for saving
  void attachTagsToItem() {
    // Clear all prevIoUs tags before adding the selected tags
    savingItem?.tags.clear();
    savingItem?.tags.addAll(enabledTagList);
  }

然后,该项目将选定的类别写入到它的 toOne 目标并保存-- saveItem 正确地在此处包含所有内容

  bool saveCategorizedItem() {
    if (selectedCategory != null) {
      // Set the item category
      savingItem!.itemCategory.target = selectedCategory;

      _userInventoryService.addCategorizedItemToLocal(savingItem!);

      return true;
    } else {
      return false;
    }
  }

它的保存位置——此时,一切都已检查完毕。我可以调试并查看它们变量中的标签和信息,我可以在 itemCategory 中查看 Category 及其信息。

  void addCategorizedItemToLocal(InitialItem saveItem) {
    _categorizedSaveBox.put(saveItem);
    print('Item saved to categorized database');
  }

Item on Saving

稍后,我查询保存的每个项目,以便将它们分组到列表中。而此时它只返回InitialItem,并没有拉取关系数据。 toOne 和 toMany 的目标都是空的。

  /// Returns all the of Items that have been categorized and saved
  List<InitialItem> getAllCategorizedItems() => _categorizedSaveBox.getAll();

------------------------------------------------------------------------------------------
Calling the query in the View Provider's class
  void getCategorizedItems() {
    _categorizedSaveList = _userInventoryService.getAllCategorizedItems();
    notify(ViewState.Idle);
  }

然后我尝试使用返回的查询构建列表。 element.itemCategory.target 返回 null,标签也是如此。正如我所说,这一切以前都在 1.0.0 版中工作,升级后失败,没有进行其他更改。一般查询有问题吗?我可以在调试窗口中查看关系,所以我假设设置正确,它似乎没有用原始查询拉出对象。 谁能解释一下我做错了什么?

  Widget categorizedList(BuildContext context) {
    final saveProvider =
        Provider.of<UserInventoryProvider>(context,listen: true);
    return GroupedListView<dynamic,String>(
      physics: const BouncingScrollPhysics(),elements: saveProvider.categorizedSaveList,groupBy: (element) => element.itemCategory.target!.categoryName,groupComparator: (d1,d2) => d2.compareto(d1),groupSeparatorBuilder: (String value) => Padding(
        padding: const EdgeInsets.all(8.0),child: Text(value,textAlign: TextAlign.center,style: TextStyles.kTextStyleWhiteLarge),),indexedItemBuilder: (c,element,index) {
        return Container();
      },);
  }

Item directly after saving,queried from store

解决方法

经过评论中的所有讨论,我终于注意到您初始化了多个商店。实际上,您正在使用多个独立数据库,因此关系无法按预期工作。您的 initializeUserInventory() 应该类似于:

void initializeUserInventory() async {
  _store = await openStore(); // new shorthand in v1.1,uses getApplicationDocumentsDirectory()
  _userQuickSaveBox = _store.box();
  _quickActionSaveBox = _store.box();
  _categorizedSaveBox = _store.box();
  _itemCategoryBox = _store.box();
  _itemTagsBox = _store.box();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。