Reputation: 39439
I have two models: Store
and Review
. Users of my site can leave a review on a store. In my database, I have a join table, reviews_stores
that associates a review with a store.
How do I link my models? I assume a Store
should haveMany Review
, and a Review
should belong to a Store
, but the join table is causing issues with CakePHP as CakePHP is assuming my reviews
table has a column called store_id
.
The reason I'm using a join table is because many parts of my site can be reviewed. For example, brands. A new Review
record will be created and a record will be inserted into a brands_reviews
table to associate the two records.
Any help would be much appreciated.
Upvotes: 0
Views: 2538
Reputation: 14808
There's no need for all the join tables for each model you can review, simple store the model name itself in a field in the Review
table.
Setup your relationship like so:
class Store extends AppModel {
public $hasMany = array(
'Review' => array('conditions' => array('Review.model' => 'Store')
);
}
You can then do this with as many extra models as you like without having to touch the database.
Upvotes: 0
Reputation: 51
Seems to me it isn't a many-many relationship but a grouped 1-many relationship. Id lose the join tables and simply have an extra table outlining which 'group' the review belongs to. So the review table would have review_id, link_id(the foreign key for the relevant brand or store), review_type_id(foreign key depicting whether the review is for a brand or store and so on). Then the review_type table only needs to have review_type_id, review_type(varchar).
Upvotes: 0
Reputation: 25698
Why are you not simply using one Review model and a reviews table with a field "foreign_key" and another field "model"? By this you do not need to duplicate tables and inherit or duplicate models. This will also remove the need for a join table.
If you want to continue to use your db design then you'll have to use a HABTM association over the hasMany association. But even in the case you want to keep that jointable, again, you can use the foreign_key/model and simply have one join table and one reviews table.
By the way, your join table review_store does not follow the conventions, it should be reviews_stores. But then it differs to the schema you've used for brands_reviews. ;)
Upvotes: 1