Vikas Vikas - 2 months ago 14
MySQL Question

how to prevent duplicate child record to database for each parent using codeigniter?

i am having product variant table in mysql, i want to prevent duplicate child record for each parent product id:




id | product id | category id | variant_value_id' | title



1 | 11 | 2 | 7

2 | 11 | 3 | 7



this is my mysql table structure.
i want to have unique variant id for each category id.
this is my controller

foreach($this->input->post('product_variant') as $value){
$variant_data = array(
'product_id' => $id,
'category_id' => $this->input->post('product_category'),
'variant_group_id' => $this->Product_model->get_variant_group_by_variant_id($value)[0]->group_id,
'variant_value_id' => $value,
'product_variant_title' => $this->input->post('product_name').' '.$this->Product_model->get_variant_group_by_variant_id($value)[0]->value,
'mrp_price' => '',
'price' =>'',
'slug' => url_title($this->input->post('product_name').'-'.$this->Product_model->get_variant_group_by_variant_id($value)[0]->value, 'dash', true),
'status' =>'',
);
if($this->Product_model->add_product_variant($variant_data)){
$this->session->set_flashdata('product_variant_added', 'Product Variant Created Succesfully');
}
}


Please help. if need more info, i will provide

Answer

If you want to prevent duplicate productId, then use the following I mean do a check:

$q = $this->db->select('ProductName')
     ->from('Table')
     ->where(array('ProductId' => $ProductId, 'variant_value_id' => $variant_value_id))->get(); //Select query to check the productId

    if($q->num_rows() == 0){ //Finally checks if the Id doesn't exist
    //Insert goes here
}
else
{
  //Already exists
}