答案 0 :(得分:2)
您可以使用以下选项之一来完成此任务:
1-您设置数据库以强制引用完整性,然后就像告诉MySQL ON DELETE CASCADE;
注意测试,但我想它应该可行。
ALTER TABLE categories
ADD FOREIGN KEY (parent_id)
REFERENCES Categories(id)
ON DELETE CASCADE;
2- Second选项以递归方式调用删除函数来完成此操作。 例如:
public function delete_category_by_id ($category_id) {
// delete this category.
$this->db->delete('categories', ['id' => $category_id]);
// fetch child categories & call the same method again.
$q = $this->db->where('parent_id', $category_id)->get('categories');
foreach( $q->result() as $Child ) {
$this->delete_category_by_id($Child->id);
}
}
这将是非常具有破坏性的这可能需要很长时间,具体取决于你有多少级别
答案 1 :(得分:1)
function delete_parent_and_child_subchild($category_id,$all_cate=array())
{
if(!is_array($category_id))
{
$this->db->where('parent_id', $category_id);
$all_cate[]=$category_id;
}
else
{
$this->db->where_in('parent_id', $category_id);
}
$get_categories= $this->db->get('newcategory');
if($get_categories->num_rows()>0)
{
$categories_vales=$get_categories->result();
$new_subcat = array();
foreach($categories_vales as $cate_val)
{
$category_id=$cate_val->category_id;
array_push($new_subcat,$category_id);
}
$all_cate = array_merge($all_cate,$new_subcat);
if(count($new_subcat)>0)
{
$this->delete_parent_and_child_subchild($new_subcat,$all_cate);
}
}
$this->db->where_in('category_id', $all_cate)->delete('newcategory');
return true;
}
答案 2 :(得分:0)
如果您根据ID删除类别,请将这些ID存储在一个变量中,然后根据parent_id = ID再次进行删除查询。
根据类别ID删除行:
$SQL = "delete from category where id=9";
根据类别ID删除子类别:
$SQL = "delete from category where parent_id=9";
或者您可以在一个查询中同时执行这两种情况。
$SQL = "delete from category where id=9 or parent_id=9";
答案 3 :(得分:0)
是的,你可以用单一查询
来做到这一点$query = "delete from category where id=1 or parent_id=1";
答案 4 :(得分:0)
<强> parent_table 强>
child_tbl_pk_id parent_table_id value
1 1 mouse
2 1 touch
3 2 fan
<强> child_table 强>
q1 = "DELETE FROM parent_table WHERE id = 1"
q2 = "DELETE FROM child_table WHERE parent_table_id = 1"
<强>查询:强>
*pTest++
答案 5 :(得分:0)
通过传递parent_id()并使用表
更改表名来运行此代码function delete_parent_and_child_subchild($category_id,$all_cate=array())
{
if(!is_array($category_id))
{
$this->db->where('parent_id', $category_id);
$all_cate[]=$category_id;
}
else
{
$this->db->where_in('parent_id', $category_id);
}
$get_categories= $this->db->get('newcategory');
if($get_categories->num_rows()>0)
{
$categories_vales=$get_categories->result();
$new_subcat = array();
foreach($categories_vales as $cate_val)
{
$category_id=$cate_val->category_id;
array_push($new_subcat,$category_id);
}
$all_cate = array_merge($all_cate,$new_subcat);
if(count($new_subcat)>0)
{
$this->delete_parent_and_child_subchild($new_subcat,$all_cate);
}
}
$this->db->where_in('category_id', $all_cate)->delete('newcategory');
return true;
}