[英]Update a many-to-many relationship in Doctrine
我有一個文章類別關系,我想在必要時更新該關系。 就是說,在文章中添加或刪除所需的類別。 我在Doctrine 1.2中使用php(ZF)設置。 在YAML中,配置看起來(簡化)如下:
Article:
columns:
id: bigint(10)
Category:
columns:
id: bigint (10)
relations:
articles:
foreignAlias: categories
class: Article
refClass: CategoryArticle
CategoryArticle:
columns:
category_id: bigint (10)
article_id: bigint (10)
relations:
category:
class: Category
foreignAlias: categoryArticle
article:
class: Article
foreignAlias: categoryArticle
我有一個堅持的文章,其中所有舊類別均可用。 通過POST請求,我得到了應該為新類別ID的列表。 到目前為止,我有:
$oldCategories = array();
foreach ($article->categories as $cat) {
$oldCategories[] = $cat->id;
}
$newCategories = $form->getValue('categories');
$diffRemove = array_diff($oldCategories, $newCategories);
$diffAdd = array_diff($newCategories, $oldCategories);
foreach ($diffRemove as $id) {
// Remove all the categories $id from article [1]
}
foreach ($diffAdd as $id) {
// Add all the categories $id to article [2]
}
我的問題是關於[1]和[2]。 添加和刪除多對多關系的最佳性能是什么?
刪除SQL中最有效的方法是使用設置了某些條件的單個sql語句,例如
delete from Products where id>3
它利用索引,分區等。
有一種方法可以使用Doctrine 1.2實現該性能值-使用DQL DELETE語句。 如文檔所示,以下查詢將轉換為上述SQL:
$q = Doctrine_Query::create()
->delete('Products p')
->where('p.id > 3');
在您的情況下,您可以使用以下方式優化刪除操作:
$q = Doctrine_Query::create()
->delete('CategoryArticle ca')
->where('ca.article_id=?', $article_id)
->andWhereIn('ca.category_id', $diffRemove);
此代碼應生成如下內容:
delete from CategoryArticle
where article_id = $article_id and category_id in ($diffremove)
插入后,您可以使用CategoryArticle
實體。 使用Doctrine進行此操作最有效的方法是建立一個實體集合,然后保存該集合:
$collection = new Doctrine_Collection('CategoryArticle');
foreach ($diffAdd as $id){
$ca = new CategoryArticle();
$ca->category = $id;
$ca->article = $article_id;
$collection[] = $ca;
}
$collection->save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.