我有两个表,它们之间有(1:1)关系。
customers table:
- customerID (PK)(AI)
- customerName
- phone
addresses table:
- customerID (PK&FK)
- address
- city
- zipcode
我尝试在相同的CodeIgniter视图表单中更新它们。
update_view.php
<th>Customer Name:</th>
<td><input type="text" name="customerName"/></td>
<tr>
<th>Customer Phone:</th>
<td><input type="text" name="phone"/></td>
<tr>
<th>Address:</th>
<td><input type="text" name="address"/></td>
<tr>
<th>City:</th>
<td><input type="text" name="city"/></td>
<tr>
<th>Zip Code:</th>
<td><input type="text" name="zipcode"/></td>
这是my controller代码的一部分:
public function insert()
{
$this->load->database();
$this->load->model('my_model');
$this->my_model->insert_entry();
$custInsert=$this->my_model->get_all_customers();
$this->load->view('main_view',array('customer'=>$custInsert));
..
}
注意:到目前为止,所有的工作都是为了处理一个表(客户)。
这是我模型文件的一部分:
function insert_entry()
{
$this->customerName = $_POST['customerName'];
$this->phone = $_POST['phone'];
$this->db->insert('customers', $this); // up to here it was working
//$customerID=$db->insert_id;
$customerID=$this->db->query("SELECT MAX(customerID) FROM `customers`");
$this->customerID;
$this->address = $_POST['address'];
$this->city = $_POST['city'];
$this->zipcode = $_POST['zipcode'];
$this->db->insert('addresses', $this);
}
至于我的问题是'地址'表需要customerID,但我不插入它的手(auto_increment)。我尝试了很多方法得到它插入到客户表后,但我不能这样做。有没有人知道不同的方法或者我应该怎么做?
这样做是一个坏主意…当新用户几乎同时出现时,你的应用该如何处理?
$customerID=$this->db->query("SELECT MAX(customerID) FROM `customers`");
你应该去掉那一行,使用更合适的方法。如果您不这样做,它可能并且将不可避免地导致您在某个时间点为客户获取错误的记录,并将地址与错误的客户相关联。
这是因为两个同时运行代码的客户端(几乎足够)可能在同一时间点遇到MAX()
,因此每个客户端都可以得到相同的值。当它们都尝试保存时,只有一个会成功,而另一个会由于主键约束而失败。这种情况称为竞态条件,应该加以防范。
用这个代替:
$this->db->insert_id()
还:
$this->customerID;
应:$this->customerID = $this->db->insert_id();
实现您想要的效果的更简洁的方法是使用数组而不是$this
。你会得到所有你需要的信息,仅此而已。有很多东西在你的$this
对象比你不需要的。
在控制器
public function insert()
{
$this->load->database();
$this->load->model('my_model');
$data_user = array(
'customerName' => $this->input->post('customerName'),
'phone' => $this->input->post('phone')
);
$data_address = array(
'address' => $this->input->post('address'),
'city' => $this->input->post('city'),
'zipcode' => $this->input->post('zipcode')
);
$this->my_model->insert_entry($data_user, $data_address);
[...]
}
在你的模型
function insert_entry($data_user, $data_address) {
$this->db->insert('customers', $data_user);
$data_address['customerID'] = $this->db->insert_id();
$this->db->insert('addresses', $data_address);
}
一个好的做法是,当你得到你的$_POST
变量时,使用Codeigniter的输入类。只需使用以下内容:
$this->input->post('VAR_NAME')
代替$_POST['VAR_NAME']