多对多关系 [英] Many to Many Relationships

查看:109
本文介绍了多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了各种不同的方式来处理Yii中的多对多关系.但是,我看到的示例还没有充实,我觉得我缺少了一些东西.

I'm seeing all sorts of different ways to handle many to many relationships in Yii. However, the examples I'm seeing aren't fully fleshed out and I feel like I'm missing something.

例如,拉里·乌尔曼(Larry Ullman)的教程未使用self :: MANY_MANY关系-

For instance, Larry Ullman's tutorial doesn't use the self::MANY_MANY relation - http://www.larryullman.com/2010/08/10/handling-related-models-in-yii-forms/

就添加和检索记录而言,在模型,控制器和视图中处理多对多的标准方法是什么?

So as far as adding and retrieving records, whats the standard way for handling Many to Many in the Model, Controller and View?

说明:我想我正在寻找一个涉及2个表的示例,该表由多对多关联,在这里我不仅可以看到两个模型,还可以看到控制器和视图,这样我就可以完全了解发生了什么.

clarification: I suppose Im looking for an example involving 2 tables, related by many-to-many, where I can see not only both models, but controllers and views as well so I can fully understand whats going on.

推荐答案

您实际上需要3个表(因此是数据透视表的额外模型),但是一旦有了它,您就可以实际使用常规的yii关系功能.

You actually need the 3 tables (so an extra model for the pivot table), but once you have it you can actually use the regular yii relation functionality.

例如,我的一个项目在购买和交易之间具有多对多的关系(请不要问为什么:)).因此,存在一个购买模型,一个事务模型和一个PurchaseToTransaction模型,它们之间建立了联系.我可以执行$ oPurchase-> transactions,Yii将使用该关系处理多对多部分,其定义如下:

For example a project of mine has a many-to-many relation between a Purchase and a Transaction (please don't ask why :) ). So there is a Purchase model, a Transaction model and a PurchaseToTransaction model that establishes links between them. I can just do a $oPurchase->transactions and Yii will handle the many-to-many part using the relation, it is defined as follows:

'transactions' => array(self::MANY_MANY, 'Transaction', 'PurchaseToTransaction(purchaseId, transactionId)')

请注意,对于交易,同样适用,但反之则相反:

Note that for the Transactions, the same applies but the other way around:

'purchases'   => array(self::MANY_MANY, 'Purchase', 'PurchaseToTransaction(transactionId, purchaseId)'),

因此 $ oPurchase->交易 $ oTransaction->购买都由Yii自动处理.

So both $oPurchase->transactions and $oTransaction->purchases are automatically handled by Yii.

总而言之,它确实可以处理多对多使用关系(至少是阅读部分,对于写作,您仍然需要任意解决方案).

In conclusion it can indeed handle Many-to-Many using relations (at least the reading part, for writing you still need arbitrary solutions).

这篇关于多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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