我正在开发一个sails应用程序,它包含多个(>2)表,需要借助populate方法加入这些表
例如
Category.js模型

attributes: {
    CategoryID:{
        type:"integer",
        required:true,
        primaryKey:true,
        autoIncrement:true
    },
    SubCategories:{                  //REFERING TO SUB-CATEGORY TABLE
        collection:'SubCategory',
        via:'CategoryID'
    },
    CategoryName:{
        type:"string",
        required:true,
        maxLength:50
    }
  }

这是SubCategory.js模型。
attributes: {
    id:{
        type:'integer',
        required:true,
        primaryKey:true,
        autoIncrement:true,
        maxLength:10,
        columnName:'SubCategoryID'
    },
    CategoryID:{
        model:'Category'                 //REFERING TO CATEGORY TABLE
    },
    ProductsOfCategory:{                  //REFERING TO PRODUCT TABLE
        collection:'Product',
        via:'SubCategoryID'
    },
    SubCategory:{
        type:"string",
        required:true,
        maxLength:50
    }
}

和Product.js模型
attributes: {
    id: {
        type: 'integer',
        primaryKey: true,
        autoIncrement: true,
        maxLength: 10,
        columnName:'ProductID'
    },
    SubCategoryID: {
        model:'SubCategory'
    },
    ProductDetails:{
        collection:'ProductDetails',
        via:'ProductID'
    },
    ProductName: {
        type: "string",
        required: true,
        maxLength: 50
    }
}

和ProductDeatils.js模型
attributes: {
    id: {
        type: 'integer',
        primaryKey: true,
        autoIncrement: true,
        maxLength: 10,
        columnName:'ProductDetailID'
    },
    ProductID:{
        model:'Product'
    },
    Size:{
        type:"string",
        required:true,
        maxLength:10
    },
    Color:{
        type:"string",
        required:true,
        maxLength:10
    }
}

在填充时,我可以填充每个类别的类别和子类别。
Category.find()
        .populate('SubCategories')
        .exec(function(err, categories){
            if (err) {
                console.log(err);
                return res.json(err);
            }
            console.log(categories);
            res.json(categories);
        })

如何一次性填充上述所有表,以便在最终查询之后,我们在一个json中获得所有上述详细信息。
我们得到上面所有表的连接
即类别包含所有子类别,子类别包含所有产品,所有产品在一个json中包含产品详细信息

最佳答案

你问了一个很好的问题。人们对将嵌套填充特性应用到sail中有着浓厚的兴趣,实际上有几十个问题请求和PRs等。
看看这里的一些历史:
[FEATURE REQUEST] Recursively populate #308-我来晚了,在2014年10月29日提出了这个要求,你将在历史上看到这一点。
据我所知,大多数对话最终都集中在这里(在sail用户请求此功能几年之后):
Deep populate #1052(截至2016年1月14日,该问题仍未解决)
从这个问题的现状来看,我们现在的处境还不清楚。这两个链接的历史确实表明了其他人使用的替代解决方案。
我的预感是递归填充不支持开箱即用。
当使用waterline模型与SailsJS关联时,我所做的是使用类似于async.js的包-使用类似瀑布的东西以编程方式显式地填充子关系。您可以将此操作与重写调用的模型的默认toJSON()相结合,以将它们的关系(您已通过编程填充)添加到JSON响应中。你同样可以选择使用内置的承诺来实现同样的目标。
找到这个(日期,2014年)SOF Question提供了更多信息。
有人,请纠正我这里,如果我错过了这个功能,在最新的帆船或水线版本-找不到任何项目的发行说明,说这是支持的。

10-04 22:14
查看更多