【问题标题】:How do i represent a many to many relationship in normalizr.js?我如何在 normalizr.js 中表示多对多关系?
【发布时间】:2018-12-24 01:12:13
【问题描述】:

我注意到库得到了很大的改进,但是我找不到如何在库中建立多对多关系。

例如,如果我有用户和 restos。我可能有“喜欢”、“访问”、“想去”等不同的多对多关系。我将如何在 normalizr.js 中对其进行规范化?

【问题讨论】:

    标签: normalizr


    【解决方案1】:

    您应该关注example of this in the normalizr repo。它需要mergeStrategyprocessStrategy 的组合:

    import { schema } from '../../src';
    
    const userProcessStrategy = (value, parent, key) => {
      switch (key) {
        case 'author':
          return { ...value, posts: [parent.id] };
        case 'commenter':
          return { ...value, comments: [parent.id] };
        default:
          return { ...value };
      }
    };
    
    const userMergeStrategy = (entityA, entityB) => {
      return {
        ...entityA,
        ...entityB,
        posts: [...(entityA.posts || []), ...(entityB.posts || [])],
        comments: [...(entityA.comments || []), ...(entityB.comments || [])]
      };
    };
    
    const user = new schema.Entity(
      'users',
      {},
      {
        mergeStrategy: userMergeStrategy,
        processStrategy: userProcessStrategy
      }
    );
    
    const comment = new schema.Entity(
      'comments',
      {
        commenter: user
      },
      {
        processStrategy: (value, parent, key) => {
          return { ...value, post: parent.id };
        }
      }
    );
    
    const post = new schema.Entity('posts', {
      author: user,
      comments: [comment]
    });
    
    export default [post];
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多