回环关系数据库hasManyThrough数据透视表
我似乎被卡在一个经典的ORM问题上,并不知道如何处理它,所以在这一点上,任何帮助是值得欢迎的。
有没有办法让一个hasManyThrough查询数据透视表? 更好的是,应用一些filter或sorting。 一个典型的例子
表产品
id,title
表类别
id,title
表产品类别
productsId, categoriesId, orderBy, main
因此,在上述情况下,假设您想获得所有类别的产品X(main = true),或者您想按orderBy
对产品类别进行sorting。
现在发生的事情是产品获取产品数据的第一个SELECT
在products_categories上的第二个SELECT
获取categoriesId
和categoriesId
的最终SELECT
以获取实际类别。 理想情况下,filter和sorting应该适用于第二个SELECT
SELECT `id`,`productsId`,`categoriesId`,`orderBy`,`main` FROM `products_categories` WHERE `productsId` IN (180) WHERE main = 1 ORDER BY `orderBy` DESC
另一个典型的例子是想要根据用户希望他们的订单来订购产品图像
所以你会有一个products_images表
id,image,productsID,orderBy
你会想
SELECT from products_images WHERE productsId In (180) ORDER BY orderBy ASC
这甚至可能吗?
编辑:这是一个中间表所需的关系,以根据我的模式得到我所需要的。
Products.hasMany(Images, { as: "Images", "foreignKey": "productsId", "through": ProductsImagesItems, scope: function (inst, filter) { return {active: 1}; } });
事情的范围function是让我获得最终的结果,而不是中间表。
我不确定是否完全理解你的问题,但是肯定你需要摆脱桌子的概念,用模型和关系来expression你的问题。
我看到它的方式,你有两个模型产品(属性:标题)和类别(属性:主)。
那么,你们之间可以有潜在的关系
-
Product belongsTo Category
-
Category hasMany Product
这意味着一个产品将属于一个类别,而一个类别可能包含许多产品。 还有其他关系可用
然后,使用生成的REST API,可以过滤GET请求以获取其属性function的项目(例如, main
),或者使用自定义GET请求(在添加关系时自动生成)来获取属于一个特定的类别。
这有帮助吗?
基于你在这里我可能会build议使用scope
选项时定义的关系。 LoopBack文档展示了一个非常类似于“产品类别”场景的例子 :
Product.hasMany(Category, { as: 'categories', scope: function(instance, filter) { return { type: instance.type }; } });
在上面的例子中, instance
是一个正在匹配的类别,每个产品都有一个新的categories
属性,该属性将包含该Product
的匹配Category
实体。 请注意,这不符合您的确切数据计划,所以您可能需要玩弄它。 此外,我认为你的API查询将不得不指定你想加载的categories
相关的数据(默认情况下不包括):
/api/Products/13?filter{"include":["categories"]}
我build议你在Product.js中定义一个自定义/远程方法,为你完成工作。
Product.getCategories(_productId){ // if you are taking product title as param instead of _productId, // you will first need to find product ID // then execute a find query on products_categories with // 1. where filter to get only main categoris and productId = _productId // 2. include filter to include product and category objects // 3. orderBy filter to sort items based on orderBy column // now you will get an array of products_categories. // Each item / object in the array will have nested objects of Product and Category. }