聞きたいことをまとめます。
カテゴリ テーブルとニュース テーブルがあります。
したがって、カテゴリには、サブカテゴリだけでなく多くのニュースを含めることができます。カテゴリを削除すると、コードはカテゴリのサブカテゴリとそのカテゴリに関連するニュースを見つける必要があり、サブカテゴリも削除する必要があります。現在、私のコードは次のようになっています(現時点ではうまく機能しています):
関係:
public $_has_many = array(
'news' => array(
'model' => 'news',
'foreign_key' => 'cat_id'
)
);
削除するコード:
/*
* @param $ids: The array of category id that we want to delete
*/
public function delete_items($ids){
if(!is_array($ids))
$ids = array($ids);
if(is_array($ids)){
$recursive = new System_Recursive();
/*
* list_items() method will simply return all records for the category table
*/
$source = $this->list_items(null);
/*
* Loop through the category ids
*/
foreach($ids as $id){
$result = $this->where('id', '=', $id)->find();
if($result->loaded()){
// If category found, then find all the news related to that category
$main_category_news = $result->news->find_all();
if($main_category_news){
// Loop through all the news and proccess the delete method
foreach($main_category_news as $main_news){
$main_news->delete();
}
}
/*
* The find_children() method returns all sub categories of the current category ($result)
*/
$recursive->find_children($source, $result->id, $arr_children, false);
if($arr_children){
// If any sub categories found, continue to loop :((, terrible
foreach($arr_children as $child){
$this->clear();
$child_result = $this->where('id', '=', $child)->find();
if($child_result->loaded()){
/*
* Again, find news related to this sub category and then loop through the news to do single delete
*/
$child_news = $child_result->news->find_all();
foreach($child_news as $c){
$c->delete();
}
}
/*
* After deleting news for sub category,
* I use clear to prevent error from loaded object
* Then find "again" the sub category to delete it
*/
$this->clear();
$child_delete = $this->where('id','=',$child)->find();
if($child_delete->loaded()){
$child_delete->delete();
}
}
}
/*
* And finally for the main direct category
*/
$this->clear();
$result = $this->where('id', '=', $id)->find();
$result->delete();
}
}
}
コードには非常に多くのループがあります。各カテゴリに関連する 500 のニュースを含む 50 のカテゴリから約 5 つのカテゴリを削除するとします。わかりませんが、このタスクを完了するには丸一日かかると思います。
それで、誰かが正しい方法でこのコードを完成させるためのヒントを教えてもらえますか? ループを減らすには?この場合、再利用する関数を作成することは可能ですか?たとえば、ニュースに多くのタグがある場合、ここで同じことを行い、そのメソッドを呼び出すだけでよいでしょうか?
これで私を助けてください。答えられない場合は、もっと意味のある質問ができるように、答えない理由も教えてください。
ありがとうございました