using transactions in CakePHP
I have two tables in a database and when I add a product I need to insert in both tables. I think that i need to use transactions, but because I'm on the learning stage of CakePHP, SQL, etc...I'm stuck.
Those are my tables
products(id, name, description, price)
images(id, path, alt, product_id)
and the method in the product model looks like this:
function newProduct($product, $image){
if(!empty($product) && !empty($image)){
$dataSource =开发者_如何学编程 $this->getDataSource();
$dataSource->begin($this);
if($this->save($product)){
ClassRegistry::init('Image');
$Image = new Image();
$Image->product_id = $this->id;
//I'm stuck here, how to save ??
return $dataSource->commit($this);
}
$dataSource->rollback($this);
}
return false;
}
There is a Transactional behavior for CakePHP 1.2+:
http://bakery.cakephp.org/articles/Jippi/2007/01/29/transaction_behavior
Cake also has a saveAll
method. Just specify both records in the same array and call saveAll:
$savearrary = array("Model1" => ..., "Model2" => ...);
$this->Model->saveAll($savearray);
(If you add Image to the $uses
array (like = var $uses = array("Image", "Product");
) you won't have to construct an Image object. The Image model will be accesible at $this->Image)
精彩评论