开发者

Many to Many Relationships

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.

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 开发者_如何学Chandling Many to Many in the Model, Controller and View?

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.


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.

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)'),

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).


I am just using Yii. Just a basic idea. If you thought One to Many is not a problem then you need to create a middle table in between like for Users and Orders, create a UsersOrders table to map those keys. Then create function to get those related tables in the class like $this->UsersOrders->Orders() for function Orders in User class, vice versa.

Many to Many is actually groundup by 3 tables. 2 tables but plus hidden table in the middle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜