41
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHPでトランザクション処理

Posted at

モデル内で処理することを想定し、Memberモデル内に書いている。
例としてmembersテーブルに$dataを保存する処理

	public function saveNewMember() {
		$datasource = $this->getDataSource();
		try{
			$datasource->begin();

			$data = array(
				'Member' => array(
					'name' => 'maeda',
					'email' => 'maeda@sample.com',
				));
			if (!$this->save($data)) {
				throw new Exception();
			}

			$datasource->commit();
		} catch(Exception $e) {
			$datasource->rollback();
		}
	}

こうした場合、以下のようになる。

	1	BEGIN
	2	INSERT INTO "public"."members" ("name", "email") VALUES ('maeda', 'maeda@sample.com')
	3	COMMIT

2つ目の処理を追加する。(別モデルにしてみる)
てっぺんに以下追加しておいて、

App::uses('Comment', 'Model');
	public function saveNewMember() {
		$this->Comment = new Comment();// 別モデル読み込み
		$datasource = $this->getDataSource();
		try{
			$datasource->begin();

			$data = array(
				'Member' => array(
					'name' => 'maeda',
					'email' => 'maeda@sample.com',
				));
			if (!$this->save($data)) {
				throw new Exception();
			}

			$data = array(
				'Comment' => array(
					'post_id' => '4',
					'comment' => 'res3-1',
				));
			if (!$this->Comment->save($data)) {
				throw new Exception();
			}

			$datasource->commit();
		} catch(Exception $e) {
			$datasource->rollback();
		}
	}

以下のように動作する。

	1	BEGIN
	2	INSERT INTO "public"."members" ("name", "email") VALUES ('maeda', 'maeda@sample.com')
	3	INSERT INTO "public"."comments" ("post_id", "comment") VALUES (4, 'res3-1')
	4	COMMIT	

Commentのpost_idに数字以外を入れて失敗させる。以下のようになる。

	1	BEGIN
	2	INSERT INTO "public"."members" ("name", "email") VALUES ('maeda', 'maeda@sample.com')
	3	ROLLBACK

つまり同じデータソースの場合は同じトランザクションになる。

41
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?