我正在 CakePHP 中组装一个包含帖子和附件的应用程序
表格如下:
Posts = id, title, datetime, content
Attachments = id, title, path, mime_type
Posts_Attachments = id, post_id, attachment_id
我对这里的关系有点困惑。到目前为止,我已经完成了:
帖子模型:
public $hasMany = array('Attachment');
和附件模型:
public $hasMany = array('Post');
但这种关系似乎并没有像预期的那样运作。谁能帮忙?
谢谢
您有两个选择:
选项 1(拥有和属于许多)
class Post extends AppModel {
public $hasAndBelongsToMany = array('Attachment');
}
class Attachment extends AppModel {
public $hasAndBelongsToMany = array('Post');
}
备选方案2(备选方案有和属于多方)
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');
}
注意:HABTM 表应按字母顺序排序,因此attachments_posts。表格应为小写并带有下划线。遵循惯例将使您的生活更轻松。
使用选项 1 具有更多"自动魔术"功能,但有时它会妨碍您。选项 2 涉及为连接表创建模型。
如果要设置帖子具有许多附件的关系,则:
帖子模型:
public $hasMany = array('Attachment');
附件模型:
public $belongsTo = array('Post');
在您的数据库中,名为"附件"的表(如果您遵循约定)应该具有外键:post_id