0

My table:

CREATE TABLE IF NOT EXISTS `detail_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `id_product` int(11) NOT NULL,
  `id_store` int(11) NOT NULL,
  `input_quality` int(11) NOT NULL,
  `output_quality` int(11) NOT NULL,
  `quality_in_store` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

I have the problem is below:

I get record have max_id, and then before i insert new record, having another process insert new record was inserted.

I think: I will lock table during "I select a record have max_id" to "I completed to insert new next record"(don't run any task work with this table). And to do this method. Please help me! How to do this by php code or Yii.

MrTo-Kane
  • 510
  • 5
  • 15

3 Answers3

1

You could use transactions:

$transaction = Yii::app()->db->beginTransaction();
try {
    foreach ($items as $item) {
        $item->attr = value;
        $item->save();
    }
    $transaction->commit();
    // actions to do on success (redirect, alert, etc.)
} catch (Exception $e) {
    $transaction->rollBack();
    // other actions to perform on fail (redirect, alert, etc.)
} 

This source code is from this post: using transaction in a loop in yii

Community
  • 1
  • 1
Germanaz0
  • 914
  • 8
  • 18
1

In Yii2, you can lock/unlock a table like this

$db = Yii::$app->getDb();
$db ->createCommand('LOCK TABLES `YOUR_TABLE` WRITE')->execute();
// access YOUR_TABLE here 
// something like YOUR_TABLE_MODEL::find()->where(["something" => "blah"])->one()
$db ->createCommand('UNLOCK TABLES')->execute();
chenzen
  • 63
  • 1
  • 1
  • 7
0

I'm not exactly sure what you want to achieve, but I'm sure it will work out if you just use transactions - http://www.yiiframework.com/doc-2.0/yii-db-transaction.html. Otherwise, you can always call a LOCK TABLE query - http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html.

$connection = Yii::app()->db;
$lock = $connection-> createCommand('LOCK TABLES `detail_transactions` WRITE');
// do your magic
$unlock = $connection-> createCommand('UNLOCK TABLES');
motanelu
  • 3,945
  • 1
  • 14
  • 21