0

How to add integrity constraint check on all controllers while inserting values to db in YII? what is the simplest method for it?

if($model->save())
                $this->redirect(array('view','id'=>$model->id));

Exception appear here

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '9-5' for key 'xyz'. The SQL statement executed was: INSERT INTO `tbl_table` (`xyz`, `x`, `x`, `x`, `x`, `x`, `x`, `created`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, NOW())
Harikrishnan
  • 9,688
  • 11
  • 84
  • 127
  • Not sure, what exactly you try to achieve - but the controller is the wrong place for this. You should put this kind of check into the models, probably in `beforeSave()`. – Michael Härtl Jun 27 '13 at 09:12
  • @RuslanPolutsygan.adding try catch everywhere where $model->save() is called seems pretty time consuming. Is there a common place where I can add this? – Harikrishnan Jun 28 '13 at 03:42

2 Answers2

0

CMysqlSchema is the class for retrieving metadata information from a MySQL database and COciSchema is the class for retrieving metadata information from an Oracle database.u can make use of the methods provided by these classes to check for the constraints for example u can make use of the method findConstraints()

Ninad
  • 1,871
  • 3
  • 15
  • 23
0
Yii->app()->db->createCommand("SET FOREIGN_KEY_CHECKS=0")->execute();

execute all your sql commands/queries here
----
----

Yii->app()->db->createCommand("SET FOREIGN_KEY_CHECKS=1")->execute();
Ricky Riccs
  • 41
  • 1
  • 5
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Dec 24 '22 at 00:27