2012-07-03 2 views
0

innoDB 기반 데이터베이스를 사용하고 있습니다. 어떻게 트랜잭션을 사용하여 데이터를 저장할 수 있습니까?CakePHP 2.1.3에서 트랜잭션 사용

사용자 배열이 있습니다. 그러나 데이터베이스의 마지막 레코드 만 저장합니다. 나는 여러 테이블에 데이터를 저장해야하고 saveAll을 모두 사용할 수 없다.

내 데이터베이스에 엄청난 수의 항목이 있기 때문에 모델 연관성을 정의 할 수도 없습니다. 따라서 매번 조인이 수행됩니다.

거래 개념을 어떻게 사용할 수 있는지 제안 해주십시오.

답변

3

모든 트랜잭션은 현재 DataSource 개체에서 수행됩니다.

첫째 있습니다 (모델)을 얻을 필요가 :

$dataSrc = $this->getDataSource(); 

This method 현재 모델에 바인딩 된 데이터 소스 개체를 반환합니다.

그럼 당신은 커밋 시작합니다 DataSource Object's methods를 사용하거나 transactions을 롤백 할 수 있습니다

$dataSrc->begin(); 
//Do something 

if (/*Everything is nice?*/) { 
    $dataSrc->commit(); 
} else { 
    //Bad things have happened 
    $dataSrc->rollback(); 
} 

당신은 물론 당신의 자신의 논리를 구현해야합니다. Cake 2.2 you can also do real nested transactions부터. Wikipedia에 따라 A "중첩 된 트랜잭션은"입니다 : 물론 모든이의

A nested transaction occurs when a new transaction is started by an instruction that is already inside an existing transaction. The new transaction is said to be nested within the existing transaction, hence the term. Nested transactions are implemented differently in different databases. However, they have in common that the changes are not made visible to any unrelated transactions until the outermost transaction has committed. This means that a commit in an inner transaction does not necessary persist updates to the database.

은 사용중인 데이터베이스에 따라 달라집니다. MySQL InnoDB transactional storage engine은 거래를 지원합니다. 이 댓글에 응답

그리고 또 다른 설명 :

Yes, I am using $this->Model->saveAll($this->request->data, array('deep' => true) in my controller. This is written under a foreach loop. And only the last foreach record is going to be saved into the database. – Arun Jain

$this->Model->saveAll();이 필요하지 않습니다 루프에서 실행되어야합니다! 그것은 당신을 위해 "자동적으로"관리 할 것입니다. 루프에서 꺼내십시오. 귀하의 질문은 트랜잭션에 관한 것이지 saveAll()을 사용하여 데이터를 저장하는 것이 아닙니다. Model::saveAll()saveMany()saveAssociated()에 대한 래퍼 일 뿐이며 모델 연결 유형에 따라 사용할 방법을 선택합니다.

읽기는 모든 아주 잘 거기에 설명되어있는 Cake Book ...

내가 사용하려고
+0

$ DATASRC = $ this-> GetDataSource() 메소드를; 그것은 나에게 오류를 준다 : 정의되지 않은 메소드의 사용. –

+1

당신은 ** 모델 **이 아닌 다른 곳에서 그것을하려고합니까? 정의되지 않은 method_ 오류의 _use를 가져 오는 다른 경우는 없습니다. –

+0

예, 저는 컨트롤러에서 $ this-> Model-> saveAll ($ this-> request-> data, array ('deep'=> true)을 사용하고 있습니다 .. 이것은 foreach 루프 아래에 작성되었으며 마지막 foreach 레코드는 데이터베이스에 저장 될 것입니다 –

관련 문제