Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 406
djt Avatar asked Mar 08 '11 01:03

djt


1 Answers

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

like image 168
Blizz Avatar answered Oct 24 '22 06:10

Blizz