【问题标题】:Keystone.js nested categoriesKeystone.js 嵌套类别
【发布时间】:2017-06-16 05:47:56
【问题描述】:

我正在尝试为 Post 模型实现嵌套类别。

我有什么:

Post.add({
    title: { type: String, required: true },
    state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true },
    author: { type: Types.Relationship, ref: 'User', index: true },
    publishedDate: { type: Types.Date, index: true, dependsOn: { state: 'published' } },
    content: {
        extended: { type: Types.Html, wysiwyg: true, height: 300 },
    },
    categories: { type: Types.Relationship, ref: 'PostCategory', index: true }
});

类别

PostCategory.add({
    name: { type: String, required: true },
    subCategories: { type: Types.TextArray }
});

现在我可以为每个类别添加一个子类别列表。 我不能做的是在创建帖子时显示子类别。此外,如果我更改类别,我需要加载与所选类别相关的子类别。

我的计划是通过手表功能实现这一点,但它似乎只适用于保存。

我正在考虑的另一件事是将子类别添加为关系,请参阅参考:

categories: { type: Types.Relationship, ref: 'PostCategory.subCategories', index: true }

但效果不佳。

所以,如果有人对如何实现这一目标有任何想法,请分享。 谢谢。

附:不要犹豫,询问任何其他信息。

【问题讨论】:

    标签: keystonejs


    【解决方案1】:

    我通过创建一个新模型“PostSubCategory”来创建嵌套类别,该模型允许用户在创建子类别时将父类别分配给子类别:

    var keystone = require('keystone');
    var Types = keystone.Field.Types;
    
    /**
    * PostSubCategory Model
    * ==================
    */
    
    var PostSubCategory = new keystone.List('PostSubCategory', {
        autokey: { from: 'name', path: 'key', unique: true },
    });
    
    PostSubCategory.add({
        name: {
        type: String,
        required: true
      },
      parentCategory: {
        type: Types.Relationship,
        ref: 'PostCategory',
        required: true,
        initial: true
      }
    });
    
    
    PostSubCategory.relationship({ ref: 'Post', path: 'subcategories' });
    
    PostSubCategory.register();
    

    然后在我的 Post.js 中,我添加一个字段来选择一个子类别,并在该字段上使用过滤器仅从所选父类别的子类别中选择子类别:

    subcategory: {
        type: Types.Relationship,
        ref: 'PostSubCategory',
        many: false,
        filters: { parentCategory: ':categories' }
    }
    

    我不确定这对于更深的嵌套效果如何,并且我在编辑帖子管理 ui 中确实存在一个问题,即更改帖子的父类别不会更新可供选择的可用子类别,直到您保存并刷新。但它让我走得更远,让父/子类别发挥作用。

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多