Keystone.js嵌套类别

时间:2017-02-26 19:48:27

标签: keystonejs

我正在尝试为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 }

但它也不起作用。

所以,如果有人有任何想法如何实现,请分享。 感谢。

P.S。不要犹豫,询问任何其他信息。

1 个答案:

答案 0 :(得分:0)

我通过创建新模型' 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' }
}

我不确定这对于更深层次的嵌套有多好用,我在编辑Post admin ui时遇到问题,更改帖子的父类别并不会更新可用的子类别以供选择直到你保存和刷新。但它让我有足够的时间让父/子类别起作用。