SQLSTATE[23000] while adding 3 entities to Doctrine 2 and Symfony 2 - mysql

I created 3 doctrine entities:
Inquiry (has many Questions),
Question (has many Answers),
Answer.
Everything works well until I try to add ANY "answer", then I get a PDOException:
[PDOException]
SQLSTATE[23000]:
Integrity constraint violation:
1452 Cannot add or update a child row:
a foreign key constraint fails
(`ankieter`.`answer`, CONSTRAINT `FK_DD714F131E27F6BF` FOREIGN KEY (`question_id`) REFERENCES `Question` (`id`))
Fixture code for testing
The error I get
EDIT:
When I export my DB structure with PhpMyAdmin, delete information about foreign keys and import the structure back, everything works well (I am able to add data to "Answer" table).
What could be wrong with the foreign keys?

I think you should try calling flush() each question creation.

Try adding cascade={"persist"} to your answers-definition in Question Entity
#ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist"})
as well as to your question-definition in Answer Entity
#ORM\ManyToOne(targetEntity="Question", inversedBy="answers", cascade={"persist"})
Now doctrine should be able to persist all entries in the correct order.

Related

Laravel On delete Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

So im trying to create a self relationship where a folder can have child folders but while deleting the parent folder i get 1451 error
Following is my Laravel migration code:
$table->foreign('f_folder_id')->references('id')->on('folders');
tell me if im not doing it the right way than what approach should i use. Thanx in advance.
(also i read somewhere setting of foreign key constraint would do it but is bad idea so im looking for advise)
You have already added a foreign key to your child table, so when you try to delete the parent row it fails because of related children on the other table.
so you have two options:
1 - to delete all the children programmatically before deleting the parent itself
2 - To let RDBMS do the children deletion on behalf of you by inforcing ondelete cascade rule.
$table->foreign('f_folder_id')
->references('id')
->on('folders')
->onDelete('cascade');
after this modification, migrate.
by the way option 2 is quick and easy.

Laravel4 Entrust - Installation issue with foreign key constraint

I am installing the laravel 4 package Entrust.
I create the migration file.
When i try to run the migration i get an error regarding the foreign key constraint.
Is this an issue pretty regarding some PhpMyAdmin settings?
I copy under the error directly from powershell:
PS C:\wamp\www\lab\x_pat> php artisan entrust:migration
Tables: roles, assigned_roles, permissions, permission_role
An migration that creates 'roles', 'assigned_roles', 'permissions', 'permission_role' tables will be created in app/data
base/migrations directory
Proceed with the migration creation? [Yes|no]yes
Creating migration...
Migration successfully created!
PS C:\wamp\www\lab\x_pat> php artisan migrate
Migration table created successfully.
[Exception]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table assigned_roles add const
raint assigned_roles_user_id_foreign foreign key (user_id) references users (id)) (Bindings: array (
))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
migrate [--bench[="..."]] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]
Foreign key constraints are not enforced by phpMyAdmin (which is a web interface) but by the MySQL server.
There are many possibilities for this error; it might be because the tables' structure do not permit it (missing indexes for example), or because of the existing data itself that does not respect the constraint you want to add.
The error is due to the missing reference on adding the foreign key (user_id) references users (id). Please ensure that the user table is exist prior to running the entrust migration.
I had to ensure my users table had its 'id' column attribute set to 'unsigned'. This matches the user_id column attribute in the entrust assigned_roles table. That allowed the migration to proceed for me.
SOLVED:
In PhpMyAdmin in had just to go in the table that contains the foreign key and press on INDEX button. In this way an index is created on that foreign key and then in RELATION VIEW is possible to assign the foreign key to the proper id of the proper table.
I think was just that the solution.
The root problem is in the file EntrustSetupTables in the migration folder, in this lines :
$table->foreign('user_id')->references('id')->on('')
->onUpdate('cascade')->onDelete('cascade');
Just put the name of the table users after the .on() and the problem will be solved.

Magento - Integrity constraint viloation: 1452, shopping cart rules

When making a discount/shopping cart rule for a given category or SKU number, it's unable to save and this error is created:
'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`shop1`.`salesrule_product_attribute`, CONSTRAINT `FK_SALESRULE_PRD_ATTR_CSTR_GROUP_ID_CSTR_GROUP_CSTR_GROUP_ID` FOREIGN KEY (`customer_group_id`) REFERENCES `customer_group` (`customer_group_i)' in /var/www/shop1/public_html/lib/Zend/Db/Statement/Pdo.php:234
I've been looking through my DB to find the problem, but without luck. I'm unsure where to start looking now, I found no obvious errors in the customer_group table, but I think it has something to do with a deleted store front, a while ago, maby messing up the customer id's?
Surely the most Obvious reason, was the last one that I checked! - The ´customer_group´ table was set to MyISAM instead of InnoDB, it must be InnoDB.

Magento - Order saving error: SQLSTATE[23000]: Integrity constraint violation

Sometimes, when we place an order in the backend - with a NEW customer, we get the following error upon submitting it:
Order saving error: SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
`artizara_artizara/enterprise_reward`, CONSTRAINT `FK_REWARD_CUSTOMER_ID`
FOREIGN KEY (`customer_id`) REFERENCES customer_entity` (`entity_id`)
ON DELETE CASCADE ON UPDATE CASCADE)
I've looked up the error log and it says the following:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint
violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(`artizara_artizara/enterprise_reward`, CONSTRAINT `FK_REWARD_CUSTOMER_ID`
FOREIGN KEY (`customer_id`) REFERENCES `customer_entity` (`entity_id`) ON DELETE
CASCADE ON UPDATE CASCADE)' in /chroot/home/artizara/artizara.com/html/lib/Zend/Db/Statement/Pdo.php:228
I've researched this in google/Magento forums and some people say it has to do with the table not being InnobDB...
So I went into phpMyAdmin and pulled up the enterprise_reward table. Opened the Operations tab. Next to Storage Engine it says InnoDB so I think I'm set there...
Other people tried making sql statements for their issue by searching for orphan data. I'm not quite sure what this is looking for exactly so I don't know how to put the sql statement together (I'm a bit newer at that anyway).
Will someone please help figure this out (making by searching for the orphan data, etc) and perhaps let me know why this has happened in the first place?
FYI - they can't give me a clear picture as to whether this happens with EVERY new customer (when placing an order in the admin) or just sometimes - so I don't have that info (yet)...
Edit 5/16 # 2:30p:
I've tried looking for orphans with this sql code but no results returned...
SELECT
*
FROM
enterprise_reward
LEFT
JOIN
customer_entity
ON enterprise_reward.customer_id = customer_entity.entity_id
WHERE
customer_entity.entity_id IS NULL
We are indeed experiencing this same issue on enterprise 1.10.0.1. This appears to be a known bug that has been filed with Varien. However - I have not found a solution.
Best thing I could find is this thread: http://www.magentocommerce.com/boards/v/viewthread/234872
The bug report I found is posted below.
BUG ID: 26516
Posted: 2011-09-21 15:22:18
When payment processing fails with an exception, the following error occurs in certain situations:
Zend_Db_Statement_Exception: SQLSTATE[23000]: Integrity constraint
violation: 1452 Cannot add or update a child row: a foreign key
constraint fails (magento_enterprise.enterprise_reward, CONSTRAINT
FK_REWARD_CUSTOMER_ID FOREIGN KEY (customer_id) REFERENCES
customer_entity (entity_id) ON DELETE CASCADE ON UPDATE CASCADE)
./lib/Zend/Db/Statement/Pdo.php:234
./lib/Zend/Db/Statement.php:300
./lib/Zend/Db/Adapter/Abstract.php:479
./lib/Zend/Db/Adapter/Pdo/Abstract.php:238
./lib/Varien/Db/Adapter/Pdo/Mysql.php:333
./lib/Zend/Db/Adapter/Abstract.php:574
./app/code/core/Mage/Core/Model/Mysql4/Abstract.php:414
./app/code/core/Mage/Core/Model/Abstract.php:318
./app/code/core/Enterprise/Reward/Model/Reward.php:202
./app/code/core/Enterprise/Reward/Model/Observer.php:548
./app/code/core/Enterprise/Reward/Model/Observer.php:564
./app/code/core/Mage/Core/Model/App.php:1265
./app/code/core/Mage/Core/Model/App.php:1246
./app/Mage.php:416
./app/code/core/Mage/Sales/Model/Service/Quote.php:187
./app/code/core/Mage/Sales/Model/Service/Quote.php:126
./EnterpriseRewardTest.php:70
Steps to reproduce:
use Magento Enterprise with Enterprise Rewards enabled (or another
module with a similar code, see below)
use a payment module that supports on-line authorization
check out an order as a new customer
trigger a payment error (e.g. by entering an invalid CC no).
I attached a PHPUnit test case that should reproduce the problem reliably.
The culprit is the code in Mage_Sales_Model_Service_Quote::submitOrder that does the following:
start a transaction
build a new order
create a new customer and fill in the order's customerId field
attempt to process the order, which raises an exception
roll back the transaction
dispatch "quote_submit_failure" event using the order as event data. Note that the order's customerId field now contains an invalid value since the transaction has been rolled back.
Now, if a handler for quote_submit_failure proceeds to use order's customerId, it will necessarily trigger the aforementioned "integrity constraint violation" error.
The problem can be reproduced on following versions:
- Magento Enterprise Edition v1.10.0.1
- Magento Community Edition v1.6.0.0 (provided there happens to be a quote_submit_failure handler that expect a valid customerId.
You can also add $this->_stmt->queryString to Zend_Db_Statement_Exception at lib/Zend/Db/Statement/Pdo.php (_execute method) to see what query is throwing the error.
It will be something like..
throw new Zend_Db_Statement_Exception($e->getMessage() . $this->_stmt->queryString, (int) $e->getCode(), $e);
But remember: do not commit core modifications in Magento. It's not cool.
Source: Aftab Naveed's Blog
If using 1.10.0.1 or less, patch this file app/code/core/Enterprise/Reward/Model/Observer.php by adding a check for customer id
protected function _revertRewardPointsForOrder(Mage_Sales_Model_Order $order)
{
// Patch for known 1.10.0.1 bug
if (!$order->getCustomer()->getId()) {
return $this;
}
// End patch
Mage::getModel('enterprise_reward/reward')
->setCustomerId($order->getCustomerId())
->setWebsiteId(Mage::app()->getStore($order->getStoreId())->getWebsiteId())
->setPointsDelta($order->getRewardPointsBalance())
->setAction(Enterprise_Reward_Model_Reward::REWARD_ACTION_REVERT)
->setActionEntity($order)
->updateRewardPoints();
return $this;
}

Grails GORM and MYSQL cascade delete problem

I have a table User that has many child tables defined in User class under the static hasMany
grails.
I have no problem when doing User.get(3).delete() in grails. It automatically delete that user and all its child table rows.
But when I want to perform the same operation in MySQL workbench. I get Error thrown by MySQL:
ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails (`test_db`.`search_stat`, CONSTRAINT `FK7A3CFFB6E64DB41` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))
SQL Statement:
DELETE FROM `test_db`.`user` WHERE `id`='3'
I dont know what is the problem here with MySQL.
Where did you read about the "ON DELETE CASCADE" in the documentation? I haven't found it here. The poster of this post had to manually add this as well to get the desired behaviour.
If grails is really supposed to add this, have you tried deleting the DB and having it re-created by grails (at least in development environment)? Maybe the current schema was generated before you added the belongsTo or something?
Also check out this Blog post about GORM Gotchas regarding hasMany and belongsTo.