如何根据另一个表ID codeigniter更新一个表

时间:2016-01-08 10:33:30

标签: php mysql codeigniter

我有两个表,第一个表与第二个表直接关联。我正在使用codeigniter和mysql作为我的数据库系统。

我的第一张表名为exam,其结构如下图所示:

exam_tbl

这是我的第二个名为exam_assign_classes的表:

exam_assign_tbl

如何根据第一个表ID更新第二个表。有时,在编辑页面中,用户可以添加指定的批次或删除批次数。我已经尝试用匹配的id计算行数并从第二个表中删除那些然后重新插入它但是它看起来很糟糕吗?

2 个答案:

答案 0 :(得分:0)

$this->db->where('`exam_id` IN (SELECT `exam_id` FROM `exam_assign_classes `)', NULL, FALSE);
$this->db->update('exam', $data); 

答案 1 :(得分:0)

这是我更新的代码版本,我在一个更新条件中放置了一堆数据库任务来更新考试分配表。

查看:

<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');
}

从上面的代码我可以实现我真正需要的。但我在更新考试分配表上的字段时正在删除和插入行。但它显示了我的应用程序性能。所以,更新数据库是否是一个好习惯?

相关问题