CakePHP 中的模型关联
我们可以在 CakePHP 中定义 4 种类型的关联(关系)
class PostsTable extends Table {
public function initialize(array $config) {
// table initialization code should be here
$this->belongsTo('Authors', [
'className' => 'Authors',
'foreignKey' => 'author_id',
'joinType' => 'INNER',
]);
$this->hasMany('Tags');
$this->hasOne('Categories');
$this->hasAndBelongsToMany('Topics');
}
}
在上面的示例中,你可以看到 4 种类型的关系
帖子属于作者 (一对一) ,它意味着在 posts 表中有一个与 authors 表的 id 相关的外键 author_id。
帖子有很多标签 (一对多) ,它意味着在 tags 表中有一个与 posts 表的 id 相关的外键 post_id。
帖子有一个标签 (多对一或一对一) ,它意味着在 posts 表中有一个外键 category_id,它与 id 表的 id 相关联。
帖子有并且属于话题 (多对多) ,这是 posts 和 topics 表之间的多对多关系。对于维护多对多关系必须要创建第三个表,表,表名应该是 posts_categories。该表的字段如下所述
- id(表的主键)
- post_id(
posts表的外键) - topic_id(
topics表的外键)