简体   繁体   中英

Cakephp hasmany, belongsto associations help needed

I am not sure how to proceed for my database schema and for my model associations, any help will be appreciated!!!

Okei, here it goes;

Model 1 : Post (id, title, category_id, tag_id, body, created, modified) Model 2 : Category (id, title, description, created, modified) Model 3 : Tag (id, title, description, created, modified)

Mu problem is how to "build" the database table to allow for multiple tags and categories, with associations.

Example: If Post 1 belongsTo category_id = 1, and hasMany Tag, tag_id: 1, 3, 8, 99 Example2: If Post 2 belongTo category_id = 1,5 and hasMany Tag, tag_id: 1, 8, 43

So basicly, I am not sure what schema to go with and the best practice to allow for multiple associations.

Any suggestions??

Thanks! -Tom

The easiest way to implement this is to use a lookup or join table. Cake uses a so-called "Has And Belongs To Many" (HABTM) relationship for these cases, which is a "many to many" relationship type.

Have a look at the manual entry for HABTM to deal with this kind of scenario. The manual mentions a comparable setup you're aiming for.

In your case you would have posts and tags tables, which are joined by a lookup table called posts_tags containing post_id and tag_id columns. If you define the HABTM relation correctly in your Post Model, Cake will know how to use the three tables correctly when saving, finding and updating data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM