使用ORMLite实现多对多关系的最好方法是什么? [英] What is the best way to implement many-to-many relationships using ORMLite?

查看:214
本文介绍了使用ORMLite实现多对多关系的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用ORMlite制作一个有表格和关系的模型。
一个关系是一个多对多关系。

I'm currently playing with ORMlite to make a model with tables and relationships. One relationship is a many-to-many relationship. What's the best way to implement that?

更具体的:

假设我有这些两个表

Product
   id
   brand

Purchase
   id

购买可以有多个产品,一个产品可以多次购买。
使用ORMLite我可以在每个模型中有一个 @ForeignCollectionField ,但我不认为它会工作。
我看到的唯一有效的解决方案是制作第三个表Product_Purchase来链接产品和购买与多对一的关系。

A purchase can have several products and one products can be in several purchases. Using ORMLite I could have a @ForeignCollectionField in each model but I don't think it would work. The only valid solution I see is to make a third table Product_Purchase to link Product and Purchase with many-to-one relationships.

你认为?

推荐答案

@ Romain的自我回答是正确的,但这里有一些更多的信息。正如他所提到的,有一个示例多对多 ORMLite 项目,演示了执行此操作的最佳方法:

@Romain's self answer is correct but here's some more information for posterity. As he mentions there is an example many-to-many ORMLite project that demonstrates the best way to do this:


http:// ormlite。 com / docs / example-many

示例使用连接表,其中包含要存储的两个对象的ID关系。在@ Romain的问题中,连接对象将同时具有 Product Purchase 对象。例如:

The example uses a join table with the id's of both of the objects to store a relationship. In @Romain's question, the join object would have both the Product and the Purchase object. Something like:

public class ProductPurchase {
    @DatabaseField(generatedId = true)
    private int id;
    @DatabaseField(foreign = true)
    private Product product;
    @DatabaseField(foreign = true)
    private Purchase purchase;
    ...
}

id字段从对象中提取创建一个表格,如:

The id fields get extracted from the objects which creates a table like:

CREATE TABLE `userpost` (`id` INTEGER AUTO_INCREMENT , `user_id` INTEGER ,
    `post_id` INTEGER , PRIMARY KEY (`id`) ) 

然后使用内部查询产品与每个购买相关联的对象,反之亦然。有关详细信息,请参阅示例项目中的 lookupPostsForUser()方法。

You then use inner queries to find the Product objects associated with each Purchase and vice versa. See lookupPostsForUser() method in the example project for the details.

有一些思考和设计工作自动执行此操作,但现在ORMLite只处理一对多的关系。

There has been some thought and design work around doing this automatically but right now ORMLite only handles one-to-many relationships internally.

这篇关于使用ORMLite实现多对多关系的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆