I'm putting together an app in CakePHP that contains both Posts and Attachments
The tables are as follows:
Posts = id, title, datetime, content
Attachments = id, title, path, mime_type
Posts_Attachments = id, post_id, attachment_id
I'm getting a bit confused with the relationship here. So far I have done:
Post Model:
public $hasMany = array('Attachment');
and Attachment Model:
public $hasMany = array('Post');
But the relationship doesn't appear to be working as expected. Can anyone help?
Thanks
You have two options:
class Post extends AppModel {
public $hasAndBelongsToMany = array('Attachment');
}
class Attachment extends AppModel {
public $hasAndBelongsToMany = array('Post');
}
class Post extends AppModel {
public $hasMany = array('AttachmentsPost');
}
class Attachment extends AppModel {
public $hasMany = array('AttachmentsPost');
}
class AttachmentsPost extends AppModel {
public $belongsTo = array('Attachment', 'Post');
}
Note: HABTM tables should be ordered in alphabetical order, so attachments_posts. And tables should be lower case and underscored. Following convention will make your life easier.
Using Option 1 has more "auto-magic" features, but sometimes it gets in your way. Option 2 involves creating a model for the join table.
If you want to set a relation where a post have many attachements then :
Post Model:
public $hasMany = array('Attachment');
Attachment Model:
public $belongsTo = array('Post');
And in your database, the table called "attachments" (if you follow the conventions) should have the foreign key : post_id