我有以下插入查询:
$salarystuff = array('salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
工资表有列:emp_no| 工资| 从_日期| to_date(我使用的是 dev.mysql.com 提供的数据库。
但它给了我一个错误 1452 说外键约束。如何引用另一个表中的键值才能插入到该表中?
这是错误消息:
无法添加或更新子行:外键约束失败 (
employees
.salaries
, CONSTRAINTsalaries_ibfk_1
FOREIGN KEY (emp_no
) REFERENCESemployees
(emp_no
) ON DELETE CASCADE)插入
salaries
(salary
,from_date
,to_date
) 值 ('1000000', '2012-12-27', '2013-01-16')
谢谢
编辑:我正在尝试以下
首先,我使用这个函数在 employees 表中创建记录:
function add_emp($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate)
{
$data = array( 'first_name' => $firstname,
'last_name' => $lastname,
'gender' => $gender,
'birth_date' => $date_of_birth,
'hire_date' => $hiredate);
$this->db->trans_start();
$this->db->insert('employees', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
$msg = "Adding the new employee failed.";
return $msg;
}
else
{
$msg = "Successfully Added Employee.";
return $msg;
}
}
然后在另一个函数中添加薪水:
function add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date)
{
$this->db->select('emp_no');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->where('gender', $gender);
$this->db->where('hire_date', $hiredate);
$this->db->where('birth_date', $date_of_birth);
$this->db->limit(1);
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
}
两者都在模型中。然后在控制器中我调用这两个函数:
$employee_insert = $this->user->add_emp($firstname,$lastname,$gender,$date_of_birth,
$jobtitle,$dept, $hiredate);
$salarythings = $this->user->add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date);
但是我收到一个错误,因为 emp_no 字段中没有值...我认为这可能是行:
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee,
我的错误信息是:
CI_DB_mysql_result 类的对象无法转换为字符串