There are 4 types of associations(relationships) we can define in CakePHP
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');
}
}
In above example, you can see 4 types of relationships
Post belongs to Author (One to One), it means in posts
table has one foreign key author_id
which is associated with id
of authors
table.
Post has many Tags (One to Many), it means in tags
table has one foreign key post_id
which is associated with id
of posts
table.
Post has one Tags (Many to One or One to One), it means in posts
table has one foreign key category_id
which is associated with id
of categories
table.
Post has and belongs to Topics (Many to Many), this is many to many relationship between posts
and topics
table. for maintain many to many relationship must need to create third table, table, table name should be posts_categories
. Fields of this table as mentioned below
posts
table)topics
table)