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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With