Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
The SQL being executed was: INSERT INTO `employee` (`client_code`, `company_name`, `emp_email`, `emp_mobile`, `emp_first_name`, `emp_last_name`) VALUES ('12345678', 'PVPPCOE', 'saurabhkulkarni2010#hotmail.com', '+449029792183', 'Saurabh', 'Kulkarni')
Error Info: Array
(
[0] => 23000
[1] => 1452
[2] => Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
)
I have three tables Client, Employee and create_client, out of which client and employee has two foreign keys.
This problem is showing when I try to insert data from create_client to employee which has exact same field.
What should I do so that I can insert two tables at one i.e create_client and employee
UPDATE-
Table Structure
1)client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
2)create_client
CREATE TABLE IF NOT EXISTS `create_client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
3)employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
This is my table structure, first user will create client that means first it will update create_client. Now if user wants he can add many employee under one client code now user will update employee table from Yii2 dynamic form widget.
For using this widget I have created one table call client this will store only client_code and company name remaining data will go in employee table e.g emp_mobile,emp_email, emp_first_name, emp_last_name.
Now this problem is pop up when user first enters data into create_client table.
everything is working between client and employee table user able to enter as many employee as it wants using Yii2 dynamic form Widget but not working for create_client
Apparently you also have a foreign key in the employee table referencing the client_code of the client table, so you can only use client_code values that already exist in the client table.
I don't know what the structure of the create_client table looks like and what its purpose is, but based on your info I assume that you should first insert the data in client, then in employee and finally in create_client, so that every foreign key's value exists in its respective table.
If this is not correct, please post your table structures and the data or queries that could be causing this.
Edit after your comment: I assume that your table structure looks like this:
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `create_client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
However, I would suggest to use client as the parent table and move the foreign key constraint to create_client, so that both employee and create_client have a foreign key of client. I would also like to normalise this and get rid of company_name in the child tables:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`),
CONSTRAINT `create_client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
The next improvement would be to use the employee table for both unique and non-unique client_code inserts. Instead of using 2 identical tables, apart from the unique key, you could do the unique validation in Yii instead of in MySQL. You can specify the table name in the tableName() method of the CreateClient model . This will remain:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This should allow you to use the dynamic form, with Client as the main model and Employee as the items model.
On Yii2 using IO Generator (Model) and MySQL I have found the following.
I have seen SET '' instead of SET NULL in update SQL statement(s) on field(s) with foreign key constraints that have caused a "Integrity constraint violation".
My "fix" is to add a default rule on the foreign key field in the model, like so:
public function rules()
{
return [
//
// your other rules
//
[['field_name_with_foreign_key'], 'default', 'value' => null],
];
}
Hope this helps someone.
remove all foreign key checks and simplify database.
the problem lies in your foreign key structure.
learn carefully about primary keys and foreign keys.
make new database again without foreign keys then check.
Related
This is my t_complaint
CREATE TABLE `t_complaint` (
`idcomplaint` int(11) NOT NULL,
`tglterima` date DEFAULT NULL,
`dept` varchar(5) DEFAULT NULL,
`pengirim` varchar(255) DEFAULT NULL,
`kontak` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`telp` varchar(255) DEFAULT NULL,
`jenis` varchar(45) DEFAULT NULL,
`uraian` text,
`uniqueid` varchar(9) DEFAULT NULL,
`responder` varchar(245) DEFAULT NULL,
`tgljawab` date DEFAULT NULL,
`jawaban` text,
`status` varchar(45) DEFAULT NULL,
`tglclose` date DEFAULT NULL,
`createddate` datetime DEFAULT NULL,
`createdby` varchar(45) DEFAULT NULL,
`modifieddate` datetime DEFAULT NULL,
`modifiedby` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and this is t_complaint_detail:
CREATE TABLE `t_complaint_detail` (
`no` int(11) NOT NULL,
`uniqueid` varchar(9) DEFAULT NULL,
`uploader` varchar(100) DEFAULT NULL,
`st_uploader` int(11) DEFAULT NULL,
`file_upload` text,
`original_name` text,
`status` int(11) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
t_complaint.idcomplaint is a primary key with Auto Increment attribute
t_complaint_detail.no is a primary key with Auto Increment attribute
I'd like to connected these table via uniqueid
I've tried ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('uniqueid') REFERENCES t_complaint('uniqueid')
The query above gives error. The error is #1005 - Can't create tablebsm.#sql-890_730(errno: 150 "Foreign key constraint is incorrectly formed") (Details…)
bsm in the error is my database (my database is bsm)
Foreign key should must be a primary key in parent table. The question is, why you are adding a redundant 'uniqueId' in both the table? You can simply define a foreign key constraint like this :
t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('idcomplaint') REFERENCES t_complaint('idcomplaint').
It should work.
Error came like this
ERROR 1215 (HY000): Cannot add foreign key constraint
Because you need to create primary key in table.you can add primary key
like this
alter table t_complaint_detail modify uniqueid varchar(20) not null;
and
alter table t_complaint_detail modify uniqueid varchar(20) not null;
after it will be works
ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY (uniqueid) REFERENCES t_complaint(uniqueid);
please read here for more reference that will be help
It's working fine for me :
Try this :
ALTER TABLE t_complaint ADD CONSTRAINT t_complaint_detail
FOREIGN KEY ( uniqueid ) REFERENCES t_complaint( uniqueid )
Reference here :
https://www.w3schools.com/sql/sql_foreignkey.asp
I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work
HI i never faced this type of problem. Please clarify me when i did wrong. I tried to generate 2 model which have relation but it didn't come in models. Here are the Db structure.
CREATE TABLE IF NOT EXISTS `property` (
`property_id` int(11) NOT NULL AUTO_INCREMENT,
`ListPrice` int(11) NOT NULL,
`ListingURL` text NOT NULL,
`ProviderName` varchar(255) NOT NULL,
`ProviderURL` text NOT NULL,
`modificationTimestamp` text NOT NULL,
PRIMARY KEY (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `location` (
`loc_id` int(11) NOT NULL AUTO_INCREMENT,
`property_id` int(11) NOT NULL,
`latitude` varchar(255) NOT NULL DEFAULT '0.0000',
`longitude` varchar(255) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`loc_id`),
KEY `property_id` (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
--
-- Constraints for table `location`
--
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk_1` FOREIGN KEY (`property_id`)
REFERENCES `property` (`property_id`) ON DELETE CASCADE ON UPDATE CASCADE;
In model no relation in there :
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
This happens sometimes with the gii tool. What you need to do is to comment the relation in the table itself. gii misses the rleationship sometimes but mostly picks it up if available in the comment. So, modify your tables and comment the foreign key as below, it should work.
CREATE TABLE IF NOT EXISTS `location` (
`loc_id` int(11) NOT NULL AUTO_INCREMENT,
`property_id` int(11) NOT NULL COMMENT 'Foreign Key (property_id) references property(property_id )',
`latitude` varchar(255) NOT NULL DEFAULT '0.0000',
`longitude` varchar(255) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`loc_id`),
KEY `property_id` (`property_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
users table:
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`unique_id` varchar(23) NOT NULL,
`full_name` varchar(100) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `unique_id` (`unique_id`) USING BTREE,
UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;
items table:
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_photo` text,
`item_name` varchar(100) DEFAULT NULL,
`item_description` varchar(500) DEFAULT NULL,
`item_price` varchar(10) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_id` (`user_id`) USING BTREE,
KEY `fk_category_id` (`category_id`) USING BTREE,
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`),
CONSTRAINT `items_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8;
What I would wanna do is to create a private messaging system for my project. Before this I have implemented a Comment system and it works well (pull out comments which has the same item_id). You can see the DDL and query here. But when it come to this, I find it hard to think about private messaging model.
Basically, the private message is to bid the item price between TWO users only (the seller and the bidder). Other registered user cannot see others bidding.
Here's my try at creating Bids table:
CREATE TABLE `bids` (
`id` int(11) NOT NULL,
`bid` float DEFAULT NULL,
`message` varchar(255) DEFAULT NULL,
`from_uid` varchar(255) DEFAULT NULL,
`to_uid` varchar(255) DEFAULT NULL,
`to_iid` int(11) DEFAULT NULL,
`time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I have also tried to make Foreign Keys into bids table, but it seems like it's already too complicated for me. So an error 1215 - Cannot add foreign key constraint came out :(
If anything just let me know.
EDIT: charset to utf8. Failed to create Foreign key constraints
MESSAGES
message_id
conversation_id
user_id
message
CONVERSATIONS
conversation_id
item_id
user_id
BIDS
bid_id
item_id
user_id
amount
I want to auto creating parent record on creating children.
Example.
CREATE TABLE IF NOT EXISTS `front_end_users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userid` int(11) unsigned NOT NULL,
`tel` varchar(20) NOT NULL,
`addr1` varchar(255) NOT NULL,
`addr2` varchar(255) NOT NULL,
`city` int(11) NOT NULL,
`zip` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(127) NOT NULL,
`username` varchar(32) NOT NULL DEFAULT '',
`password` char(64) NOT NULL,
`logins` int(10) unsigned NOT NULL DEFAULT '0',
`last_login` int(10) unsigned DEFAULT NULL,
`reset_token` char(64) NOT NULL DEFAULT '',
`status` varchar(20) NOT NULL DEFAULT '',
`last_failed_login` datetime NOT NULL,
`failed_login_count` int(11) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username` (`username`),
UNIQUE KEY `uniq_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `promouter` (
`userid` int(10) unsigned NOT NULL,
`balance` float NOT NULL,
`commision` float NOT NULL,
`mountly_fee` float NOT NULL,
`verified` tinyint(1) NOT NULL DEFAULT '0',
KEY `promouter_ibfk_1` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `front_end_users`
ADD CONSTRAINT `front_end_users_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE;
ALTER TABLE `promouter`
ADD CONSTRAINT `promouter_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `front_end_users` (`userid`) ON DELETE CASCADE;
users->front_end_users->promouter
I want if I create promouter with login, password and address than automatically inserts appropriate fields in users (login, password), front_end_users (addr1, addr2, userid) and promouter (userid).
And I have several roles. So I can not add have_one to user model. But I added have_one to front_end_users and promouter models.
If you want to trigger parent creation on child creation then I think you should use trigger(s) on database level.
EDIT:
Create a table with the following scheme:
Rules(ID, TableName, ColumnName, Event, Action, Parameters)
You will have a set of Rules then and you will be able to make a general implementation for this. In your business layer you will call your rule parser (which also has to be implemented by you) and this way you can make any logical triggers in your business layer. I hope this helps.