CASCADE Many-to-Many Relationships with PHP Doctrine
Mar 10, 2008 in PHP, Doctrine, and Backend
In Doctrine, creating Many-to-Many relationship is documented well and easy to implement using the 0.10.2 branch. Properly cascading ON DELETE properly is not-so-well documented.
The solution is to add four more relations to each of the entity classes involved in the Many-to-Many relationship. The following example describes a Many-to-Many relationship between Articles and ArticleCategories.
The Articles Entity Class
abstract class BaseArticles extends Doctrine_Record{
public function setTableDefinition(){
$this->setTableName('articles');
$this->hasColumn('id', 'integer', 20, array('notnull' => true, 'primary' => true, 'autoincrement' => true));
// ...
}
public function setUp(){
$this->hasMany('ArticleCategories', array('refClass' => 'ArticlesArticleCategories',
'local' => 'articles_id',
'foreign' => 'article_categories_id'));
// This relation must be added
$this->hasMany('ArticlesArticleCategories', array('local' => 'id',
'foreign' => 'articles_id'));
}
}
The Categories Entity Class
abstract class BaseArticleCategories extends Doctrine_Record{
public function setTableDefinition(){
$this->setTableName('article_categories');
$this->hasColumn('id', 'integer', 20, array('notnull' => true, 'primary' => true, 'autoincrement' => true));
// ...
}
public function setUp(){
$this->hasMany('Articles', array('refClass' => 'ArticlesArticleCategories',
'local' => 'article_categories_id',
'foreign' => 'articles_id'));
// This relation must be added
$this->hasMany('ArticlesArticleCategories', array('local' => 'id',
'foreign' => 'article_categories_id'));
}
}
The ArticlesArticleCategories "Reference" Entity Class
abstract class BaseArticlesArticleCategories extends Doctrine_Record{
public function setTableDefinition(){
$this->setTableName('articles_article_categories');
$this->hasColumn('articles_id', 'integer', 20, array('primary' => true));
$this->hasColumn('article_categories_id', 'integer', 20, array('primary' => true));
}
public function setUp(){
// These two relations must be added
$this->hasOne('Articles', array('local' => 'articles_id',
'foreign' => 'id',
'onDelete' => 'CASCADE'));
$this->hasOne('ArticleCategories', array('local' => 'article_categories_id',
'foreign' => 'id',
'onDelete' => 'CASCADE'));
}
}
When an Article or ArticleCategories entity is deleted, all ArticlesArticleCategories entities will be deleted too. This ensures the articles_article_categories table will remain clean at all times.
D4Ly..com ©2006