我有两个表,第一个表与第二个表直接关联。我使用codeigniter和mysql作为我的数据库系统。如何根据另一个表ID更新一个表codeigniter
我的第一台名为exam
及其下面的画面结构:
这是我的第二个表称为exam_assign_classes
:
如何更新基于第二个表在第一张桌子上。有时在编辑页面中,用户可以添加已分配批次或删除批次数量。我已经尝试过使用匹配的id来计算行数,并从第二个表中删除它们,然后重新插入它,但这似乎很糟糕的做法?
我有两个表,第一个表与第二个表直接关联。我使用codeigniter和mysql作为我的数据库系统。如何根据另一个表ID更新一个表codeigniter
我的第一台名为exam
及其下面的画面结构:
这是我的第二个表称为exam_assign_classes
:
如何更新基于第二个表在第一张桌子上。有时在编辑页面中,用户可以添加已分配批次或删除批次数量。我已经尝试过使用匹配的id来计算行数,并从第二个表中删除它们,然后重新插入它,但这似乎很糟糕的做法?
$this->db->where('`exam_id` IN (SELECT `exam_id` FROM `exam_assign_classes `)', NULL, FALSE);
$this->db->update('exam', $data);
,这是我更新代码,我放在一堆数据库任务的一个更新状态更新考试分配表版本。
查看:
<div class="form-group col-xs-12 col-sm-6 col-md-4">
<span class="input-group-addon"><i class="fa fa-asterisk" aria-hidden="true"></i> <i class="fa fa-calendar" aria-hidden="true"></i> <?php echo get_phrase('select_batchs'); ?></span>
<select class="form-control" name="assigned_batch[]" data-plugin="select2" multiple>
<?php
foreach($program_list as $program):
$batch_list = $this->crud_model->get_batchs_by_program_id($program['program_id']);
?>
<optgroup label="<?php echo $program['name']; ?>">
<?php foreach($batch_list as $batch): ?>
<option value="<?php echo $batch['batch_id']; ?>" <?php foreach($assigned_batchs as $assignedRow){ if($assignedRow['batch_id'] == $batch['batch_id']) echo 'selected';} ?>><?php echo $batch['batch_name']; ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>
</div>
型号:
public function delete_associated_exam_assign($exam_id = '')
{
$this->db->where('exam_id', $exam_id);
$this->db->delete('exam_assign_classes');
return true;
}
public function insert_associated_exam_assign($data2){
$this->db->insert('exam_assign_classes', $data2);
return true;
}
if($param1 == 'do_update'){
$data['name'] = $this->input->post('exam_title');
$data['start_date'] = $this->input->post('start');
$data['end_date'] = $this->input->post('end');
$data['status'] = $this->input->post('status');
if(isset($_POST['is_entrance'])):
$data['entrance_exam'] = $this->input->post('is_entrance');
endif;
$exam_id = $param2;
// update exam table
$this->crud_model->update_exam_details($exam_id, $data);
// update exam assign table
/*First of all delete all those associated rows with matching ids*/
$this->crud_model->delete_associated_exam_assign($exam_id);
/*insert newly assign classes*/
foreach($this->input->post('assigned_batch[]') as $batchs){
$data2['exam_id'] = $exam_id;
$data2['batch_id'] = $batchs;
$this->crud_model->insert_associated_exam_assign($data2);
}
$this->session->set_flashdata('flash_message' , get_phrase('data_updated'));
redirect(base_url() . 'index.php?admin/exam_list/', 'refresh');
}
从上面的代码我可以实现我真正需要的东西。但我正在删除和插入行,同时更新考试分配表上的字段。但它显示了我的应用程序性能。所以,这是一个很好的做法或不更新数据库?
实际上,我需要更新第二张表exam_assign_classes,它将有许多行与exam_id关联。我试过你的解决方案,但没有任何反应。我将发布我的模式和控制器代码来更新考试记录。请查看我的代码 –