简体   繁体   中英

How do you make a foreign key for a new row in a table? - mysql - CodeIgniter

I can't get my head around foreign keys. I'm getting a database error 1452 saying cannot add/update a child row, and I haven't got a clue what that means.

I'm assuming from browsing around for the answer that you need to get the value from another table, but am not sure if that's right.

I'm trying to insert a row in a table, which leads to that error. How do I specify the value for the foreign key like I did with the other values I wanted to insert using CI?

Please help

Here is what I'm trying to insert:

$salarystuff = array('salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);

The table salaries has columns for: emp_no,salary,to date and from date. I've inserted everything except the id as seen above, but the id is needed from another table. Here is the error message:

Cannot add or update a child row: a foreign key constraint fails ( employees . salaries , CONSTRAINT salaries_ibfk_1 FOREIGN KEY ( emp_no ) REFERENCES employees ( emp_no ) ON DELETE CASCADE)

I'm getting a database error 1452 saying cannot add/update a child row, and I haven't got a clue what that means.

It usually means that the table you're trying to insert a row into has at least one column that holds a foreign key reference to another table. That means whatever value you provide for that column must already exist in that other table. (It doesn't make sense to store a salary for an employee who doesn't exist.)

Cannot add or update a child row: a foreign key constraint fails (employees.salaries, CONSTRAINT salaries_ibfk_1 FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE)

When you insert a row into "salaries", the value you provide for "emp_no" must already exist in "employees".

All the possible values are in "employees.emp_no". How you pick the right "emp_no" from among all those possible values is application-dependent.

Most of the time, we'd expect a user to pick an employee number from a drop-down list of employee numbers and employee names, and then fill in the new salary. Whether the user fills in "from date" and "to date" or whether that's done automatically is application-dependent. After the user picks a name and supplies a salary, and after the "from date" and "to date" are filled in either by the user or calculated by code, you can insert those values into "salaries" as a new row.

In any case, as far as the database insert statement is concerned, your CI code should deal with "emp_no" exactly like it deals with all the other columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM