MySQL import. #1452 - Cannot add or update a child row: a foreign key constraint fails - mysql-error-1452

I've tried importing an SQL file into an empty database in PHP MyAdmin and I have been presented with the following error:
SQL query:
customer_eav_attribute` ADD CONSTRAINT `FK_CSTR_EAV_ATTR_ATTR_ID_EAV_ATTR_ATTR_ID`
FOREIGN KEY (`attribute_id`)
REFERENCES `eav_attribute` (`attribute_id`)
ON DELETE CASCADE ON UPDATE CASCADE
MySQL said: Documentation
#1452 - Cannot add or update a child row:
a foreign key constraint fails (`example_db_name`.
`#sql-1ab1_b9d4`, CONSTRAINT `FK_CSTR_EAV_ATTR_ATTR_ID_EAV_ATTR_ATTR_ID`
FOREIGN KEY (`attribute_id`) REFERENCES
`eav_attribute` (`attribute_id`) ON DELETE
CASCADE ON UPDATE CASCA)
I have no idea what it means, what do I need to do to fix this?
thank you :)

might be due to the order of the create table statement in the SQL file, move the create statement of the reference table "eav_attribute" before add constraint statements

Related

Deleting Entity with Foreign Key Relationship Without Deleting Reference Object

My problem is with the generic "Delete" in the BidController I am getting the typical Error:
The DELETE statement conflicted with the REFERENCE constraint "fkw_....". The conflict occurred in database table ..., column ....
The statement has been terminated.
Thank you so much for any and all help.
Try updating the ActiveBidId with a null value and then delete the bids.That way you break the link between the Item and Bid and than you can remove the Data from Bids.
Try making the relationship as OPTIONAL. This way your items can have null Foreign Keys.
If you are using database first approach:
CREATE TABLE Item(
ItemId INT PRIMARY KEY,
ActiveBidId INT NULL FOREIGN KEY REFERENCES Bid(BidId)
// ...
);
If you already created the table, then you can alter your table as follows:
ALTER TABLE Item
DROP CONSTRAINT FK_ActiveBidConstraint -- The name of your constraint
GO
ALTER TABLE Item
ADD CONSTRAINT FK_ActiveBidConstraint FOREIGN KEY (ActiveBidId) -- The name of your constraint
REFERENCES Bid(BidId);
Apparently I am able to set the GUID to null, so I am posting a simple answer.
In my BidController I have updated my code:
item = null;
This removes the reference to the bid and so the bids are free to be removed!

rails & postgreSQL - How can I update a data with existing primary key?

I want to update some data in Lecture(id, name, etc.) table.
For example, there is a data(id: 1, name: "first") in the Lecture.
When I typed Lecture.create(id: 1, name: "newer") =>
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey"
Is there any way to update data?
Try this:
Lecture.find(1).update(name: "newer")
Find more information on update here: http://guides.rubyonrails.org/active_record_basics.html#update
The reason it didn't work is because the id is unique. When you were using create, it was trying to create a NEW record with id of 1, not edit the same record.
PG::UniqueViolation: ERROR: duplicate key value violates unique
constraint "lectures_pkey"
id is the default primary key which shouldn't be changed or duplicated. As you are inserting a row with an existing id, you get that error.
Instead, you need to do like below.
#lecture = Lecture.find(1)
#lecture.update_attributes(name: "newer")
You can use
lec = Lecture.find(1)
lec.update_attributes(name: "newer")
You are getting error PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey" due to you can not create record with same id. Id is primary key in table.
All of the current answers are correct if you don't mind loading the record and then updating it. If you don't need to actually load the record, and just want to update data in the database you can do
Lecture.where(id: 1).update_all(name: "newer")
This will skip all validations, etc and just do a direct sql update of the data in the database of the record with id == 1

Informix 4GL and triggers

I want a simple SQL (trigger) for duplicate checking.
My table name is test1 with 2 columns, code and sname. Before inserting a new record, check if the record already exists: if it does, generate an error and do not insert; if it does not, let the insert proceed.
How do I do that?
The simplest, most reliable way to ensure that there is no duplicate data in the table is not using triggers at all, but using UNIQUE or PRIMARY KEY constraints:
CREATE TABLE test1
(
code INTEGER NOT NULL PRIMARY KEY,
sname VARCHAR(32) NOT NULL UNIQUE
);
The four constraints (two NOT NULL, one PRIMARY KEY, one UNIQUE) automatically ensure that no duplicate records are inserted into the table.
If you choose to add a trigger, it will be duplicating the work that is done by these constraints.
As to how to do it, you will need to create a stored procedure which is invoked from the trigger statement. It will be given the new code and new name, and will do a SELECT to see whether any matching record occurs, and will raise an exception if it does and will not raise an exception if not.
CREATE PROCEDURE trig_insert_test1(ncode INTEGER, nname VARCHAR(32))
DEFINE ocode INTEGER;
FOREACH SELECT code INTO ocode
FROM test1
WHERE code = ncode OR sname = nname
RAISE EXCEPTION -271, -100, "Value to be inserted already exists in table test1";
END FOREACH;
END PROCEDURE
Then you use:
CREATE TRIGGER ins_test1 INSERT ON test1
REFERENCING NEW AS NEW
FOR EACH ROW (EXECUTE PROCEDURE ins_trig_test1(new.code, new.sname))
In Informix 4GL, you can either create strings containing these statements, and then PREPARE and EXECUTE (and FREE) them, or you can use SQL blocks:
SQL
CREATE TRIGGER ins_test1 INSERT ON test1
REFERENCING NEW AS NEW
FOR EACH ROW (EXECUTE PROCEDURE ins_trig_test1(new.code, new.sname))
END SQL
But, as I said at the outset, using triggers for this is not the best way to go; it is redundant given the table definition.
I've not run any of the SQL or SPL past the server; you'll need to check that the semi-colons are in the right places in the SPL, as SPL is fussy about that.
You can find the syntax for the SQL and SPL statements in the Informix 11.70 Information Centre.

Update part of primary key Entity Framework 4.0

I've a table with a compose primary key (3 columns):
UTP_ID (ITEMId)
UTS_ID (CategoryID)
USS_ID (SubCategoryID)
When I try to change SubCategory ,for example,with EF 4 i get follow error:
utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);
the property is part of the object's key information and cannot be modified
Any Ideias?Why i can't change it?
EF implements an Identity Map between primary key property values and object references. It doesn't allow to change the key for the same object instance.
I would do this with direct SQL:
objectContext.ExecuteStoreCommand(
"UPDATE MyTable SET USS_ID = {0} WHERE UTP_ID = {1} AND UTS_ID = {2} AND USS_ID = {3}",
Convert.ToInt32(ddlSubSetor.SelectedItem.Value),
utl.UTP_ID, utl.UTS_ID, utl.USS_ID);
Make sure that your entity utl is detached from the context because this code directly writes into the database table and the entity doesn't get any information about this change. But this avoids having to delete and recreate the entity (which might be impossible due to existing foreign key constraints on the old row in the database).
As a result of being part of the entity key the object needs to be deleted from the context and re-attached with the new primary key value.
The Entity Framework works by having a context which manages the state of the entities, a collection of entities (basically the table) and the entity itself (a row of data). As data is read from the database it is added to the entity's collection which in turn is managed by the context for changes of state. Changing an Entity's key is really deleting the entry from the database and inserting a new one. As a result to change an entity key, first delete the entity from it's collection, detach the entity object to allow key modification, change the primary key value and re-attach the entity to the collection. Finally call save changes in the context to apply the changes to the database.
The following code should produce the desired results:
Context.UTLs.DeleteObject(utl);
Context.UTLs.Detach(utl);
Context.SaveChanges();
utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);
Context.UTLs.AddObject(utl).
Context.SaveChanges();

Symfony - Try to update a record in DB with some foreign keys

Thanks a lot for recent help. It works really well, but now I am having some problems with this code.
//Save course record to DB
$record_course = new course();
$record_course->setName($courseInfo['name']);
$record_course->setUrl($courseInfo['url']);
$record_course->setAcronym($courseInfo['acronym']);
$record_course->setCourseTypeId($record_courseType->getId());
$record_course->setStartDate($courseInfo['startDate']);
$record_course->setCollegeId($record_college->getId());
$record_course->setPlanUrl($courseInfo['planUrl']);
$record_course->replace();
As you can see, I try to update a record but now we have some foreign keys. In this case is CourseTypeId and CollegeId. When i try to replace this record i get next message:
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (grabmark.course, CONSTRAINT course_course_type_id_course_type_id FOREIGN KEY (course_type_id) REFERENCES course_type (id))"
Anyone can help me please?
Sorry, but i am initiate now in symfony and it's my first contact with an MVC Framework.
Thanks a lot,
Alexandre Sousa
Alexandre, this is more of a database issue than symfony.
When you attempt to update this record, you are changing CourseTypeId and CollegeId with new values and these according to you are foreign keys. Are the values in these fields (CourseTypeId and CollegeId) present in the table where these keys are being referenced from?
For example:
Lets say you are setting CourseTypeId to 15 and CollegeId to 10, then are the values 15 and 10 also present in the database table from where these foreign keys are being referenced? If not, then the Integrity constraint error you are experiencing shows up. Since you are UPDATING and not really INSERTING, then the values 15 and 10 must be present in the table from where the two foreign key columns are referencing.
Does this help?

Resources