I’m building a web application using Yii framework, and i’m quite new to it.
I have 3 db tables. One stores users, the second products, and the third is a relationship table that stores user_id, product_id and more info like the time the product was bought.
I configured a MANY_MANY relationship, and have no problem to get all the products the user has bought. However I can’t figure out how can I get the extra info from the relationship table?
Thank you
If your association holds additional data, you can declare itself as a class
Purchaseand add these relationships:Remove remaining
MANY_MANYrelationships fromUserandProductmodels. Note the usage of through relationship. Fetching data might look like this:This will perform only one query from
Usertable joining on another two tables. AlsoUser::model()->with('products')will efficiently find user(s) with products they bought. Your DB scheme can remain the same, except you’ll need to add composite primary key in the association table.See this article in the Yii wiki for a detailed explanation.