symfony - Unique Constraint How to determine that the same data already exists before saving?
大家讲道理
大家讲道理 2017-05-16 16:44:44
0
2
757
if(!$workflow_entity = $em->getRepository('AlbatrossAceBundle:Workflow')->findByIdAndStatus($line[$titleArr['WorkflowStepID']],$line[$titleArr['WorkflowStatus']])){
                        $workflow_entity = new Workflow();
                        $workflow_entity->setWorkflowStatus($line[$titleArr['WorkflowStatus']]);
                        $workflow_entity->setWorkflowStepID($line[$titleArr['WorkflowStepID']]);
                        $em->persist($workflow_entity);
}

I only check if the same data already exists in the current database,
But there are already several pieces of the same data in the data being inserted.
So during the insertion operation, this information is given
An exception occurred while executing 'INSERT INTO workflow (workflow_step_id, workflow_status) VALUES (?, ?)' with params ["10", "Assigned"]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10-Assigned' for key 'stepid_status_uniq'

  uniqueConstraints:
    stepid_status_uniq:
        columns: [ workflow_step_id, workflow_status ]

I have created a unique constraint in the database (I don’t know if this is correct)
But the data that is being inserted now has the same data before flash
How do I know that the current data violates the unique rule before saving it to the database?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
小葫芦

You can query once before inserting according to your constraint rules. For example, according to your example, query first

SELECT count(*) FROM workflow WHERE workflow_step_id='10' AND workflow_status='Assigned'

If the result is not 0, it means that continuing to insert will violate the unique rule.

Of course, this is actually not recommended. It is very resource intensive to check every time you insert it
You can consider using

INSERT IGNORE INTO

Then check affected_rows after inserting. If it returns 0, it means the data insertion failed. At this time, check whether the constraint rules are violated.

滿天的星座

You should use Validation,

http://symfony.com/doc/master/reference/constraints/UniqueEntity.html

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!