简体   繁体   中英

Delete record if it doesn't have child record related to it in codeigniter

I have a shop table and item table guys. So I want to delete shop from shop table. Shop should be deleted if it doesn't have any item and can't delete if it has item. The code written here is not deleting shop whether there is an item or not. This is my controller:

public function deleteShop()
    {
        if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
        {
            redirect('auth/login', 'refresh');
        }
        else
        {    
            $id = 0;        
            $shop_id = $_GET['shop_id']; 
            $results = $this->shop_model->getShopIdFromItem($shop_id);


            if($results) {
                    foreach ($results as $key) {
                        $id = $key->shop_id;
                    }
                    if($id == $shop_id) {
                        $this->session->set_flashdata('message', 'There is an item with this Shop. You cannot delete this!');
                        redirect(base_url() . 'admin/shop','refresh');
                    }
                } else {
                    $result = true;
                    if($result) {
                        redirect(base_url() . 'admin/shop', 'refresh');
                    } else {
                        echo "Something went wrong!";
                    }
                }
        }

This is my model:

function getShopIdFromItem($shop_id) {
        $this->db->select('category_id');
        $this->db->from('item');
        $this->db->where('shop_id', $shop_id);
        $query = $this->db->get();
        if($query->num_rows() > 0) {
            return $query->result();
        } else {
            return false;
        }
    }

    function delete($shop_id)
    {
        $this->db->where('shop_id', $shop_id);
        $this->db->delete('shop'); 
        return $this->db->affected_rows();
    }
function delete($shop_id)
{
$this->db->from('item');
$this->db->where('shop_id', $shop_id);
$query = $this->db->get();
if($query->num_rows() == 0) {
    $this->db->where('shop_id', $shop_id);
    $this->db->delete('shop'); 
    return $this->db->affected_rows();
} else {
    return false;
}

change your delete method ... it will only delete if it dose not have any item available ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM