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

查看:176
本文介绍了什么是实现使用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.

你是什么人想的?

推荐答案

@罗曼的自我的答案是正确的,但这里是留给后人的更多信息。当他提到有一个例子很多一对多 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的两个对象的存储关系。在@罗曼的问题,参加对象有两个产品购买对象。是这样的:

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天全站免登陆