search

Home  >  Q&A  >  body text

symfony - Unique Constraint How to determine that the same data already exists before saving?

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?

大家讲道理大家讲道理2750 days ago774

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-16 16:46:44

    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.

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 16:46:44

    You should use Validation,

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

    reply
    0
  • Cancelreply