简体   繁体   中英

How to update a NULL foreign key and create a new row within another table referencing the same key?

I have two tables, users and hubs . Once the user creates an account, my backend will make a new row within the users table (filling in all columns of the row except the hubID column as it is not known yet).

Once the user has signed up, they are greeted with a setup screen, to which where they will obtain a hubID from an external product that the app connects to. I want to then update their user row inside the users table and add the hubID to their row (which is currently null) AND at the same time add a new row inside the hubs table where the primary key will be the hubID (as it will always be unique).

The Users table has the foreign key to reference a row inside the hubs table .

Users table

+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| UserID   | int(11)     | NO   | PRI | NULL    | auto_increment |
| Username | varchar(25) | NO   |     |         |                |
| Email    | varchar(25) | NO   |     |         |                |
| Password | varchar(50) | NO   |     |         |                |
| hubID    | varchar(50) | YES  |     |         | foreign_key    |
+----------+-------------+------+-----+---------+----------------+

Hubs Table

+-----------+------------+------+-----+---------+----------------+
| Field     | Type       | Null | Key | Default | Extra          |
+-----------+------------+------+-----+---------+----------------+
| hubID     | varchar(50)| NO   | PRI |         |                |
| isSetup   | BOOLEAN    | NO   |     | 0       |                |
| SWVersion | DOUBLE(2,3)| NO   |     | 0.1     |                |
| dateAdded | TIMESTAMP  | NO   |     |         |                |
+-----------+------------+------+-----+---------+----------------+

At the moment, I am using the query:

update users set hubID = 'hub123' where userID = '1';

to add the new hubID to the relevant row inside the users table . But I am getting this error:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`database`.`users`, CONSTRAINT `fk_users_hubs1` FOREIGN KEY (`hubID`) REFERENCES `hubs` (`hubID`) ON DELETE CASCADE ON UPDATE CASCADE)

I don't know how one would update a foreign key AND add a new row within a different table with the same key so they both represent each other. My model at the moment would work if I knew the hubID when creating the user's row , but that simply is impossible for my design.

This is the script:

users table :

CREATE TABLE IF NOT EXISTS `database`.`users` (
  `userID` INT NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) NOT NULL,
  `email` VARCHAR(255) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `hubID` VARCHAR(50) NULL,
  PRIMARY KEY (`userID`),
  INDEX `fk_users_hubs1_idx` (`hubID` ASC) VISIBLE,
  CONSTRAINT `fk_users_hubs1`
    FOREIGN KEY (`hubID`)
    REFERENCES `database`.`hubs` (`hubID`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

hubs table :

CREATE TABLE IF NOT EXISTS `database`.`hubs` (
  `hubID` VARCHAR(50) NOT NULL,
  `isSetup` TINYINT NOT NULL DEFAULT 0,
  `hubSWVersion` DECIMAL(3,2) NOT NULL DEFAULT 0.1,
  `dateAdded` DATETIME NOT NULL,
   PRIMARY KEY (`hubID`))
ENGINE = InnoDB;

You probably want user.username to be unique also. Anyway, I am assuming it is. Even if it isn't there is a remedy I will describe later. The solution is simply doing inserts in the correct order. For example:

insert into users(username, email, password) values('Booboo', 'Booboo@nowhere.atall', 'password');
insert into hubs(hubID, isSetup, dateAdded) values('hubBooboo', 1, now());
update users set hubId = 'hubBooboo' where username = 'Booboo';

See db-fiddle

I am assuming that because username columns are unique I can do the last update by using the known username . But even if that assumption is not correct, you can always retrieve the last inserted autoinsert key (ie column userId ) with SELECT LAST_INSERT_ID() and then use column userId in the where clause.

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