如果我从表中删除整行并将该行的两列值插入到另一个表中,我的模型函数结构应该是什么?我想使用事件记录。
function foo()
{
$this->db->truncate('to');
$query = $this->db->get('from')->result(); // get first table
foreach($query as $row) // loop over results
{
$this->db->insert('to', $row); // insert each row to another table
}
}
这正在移动整行。我只想要两个特定的列。我该怎么办?
编辑 这是正确的方法吗?
public function refund()
{
$id = $this->uri->segment(4);
$data['accounts'] = $this->accounts_model->get_accounts_data_by_id($id);
foreach ($accounts as $row)
{
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
$this->db-insert('refund',$data);
}
最佳答案
Controller :
class Controllername extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('your_model');
}
public function somename()
{
$id = 6; // Row id to delete
$this->your_model->delete_table1($id);
$data = array(
array(
'col1' => 'val1',
'col2' => 'val2',
'col3' => 'val3',
),
array(
'col1' => 'val1',
'col2' => 'val2',
'col3' => 'val3',
),
);
$this->your_model->insert_table2($data);
}
}
型号:
class Your_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->db = $this->load->database('default',true);
}
public function delete_table1($id)
{
$this->db->delete('table1', array('id' => $id));
}
public function insert_table2($data)
{
$this->db->insert_batch('table2', $data);
}
}
说明:
1) 创建一个函数,在其中调用模型函数,该函数提供要从 table1< 中删除的行的
。$id
参数
2) 第二个模型函数调用向 table2
插入 2 行,提供数组作为参数并使用 insert_batch()
事件记录功能。
3) 在执行上述任务之前,不要忘记在 Controller 构造函数中加载模型
。
关于mysql - 使用事件记录将一行移动到另一个表但特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24464255/