Моя схема базы данных:
CREATE TABLE IF NOT EXISTS `costumers` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`person_id` smallint(5) unsigned NOT NULL,
`status` tinyint(1) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `fk_costumers_persons_idx` (`person_id`)
);
CREATE TABLE IF NOT EXISTS `persons` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`phone` char(10) DEFAULT NULL,
`mobile` char(10) DEFAULT NULL,
`email` varchar(64) NOT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`data_updated` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
Вот мой код контроллера:
class Test extends CI_Controller {
public function index()
{
// Faking POST values
$_POST = array(
// Person info
'name' => 'Paulo Freitas',
'phone' => 'xxxxxxxxxx',
'email' => '[email protected]',
// Costumer info
'status' => 2
);
// Utility function
function factory_from($class, $fields)
{
$CI =& get_instance();
$input = array();
foreach ($fields as $field) {
$input[$field] = $CI->input->post($field) ?: null;
}
$obj = new $class;
$obj->from_array($input);
return $obj;
}
// Save person
$person = factory_from('Person', array(
'name',
'phone',
'mobile',
'email'
));
$person->save();
// Save costumer
$costumer = factory_from('Costumer', array(
'status'
));
$costumer->save($person);
var_dump($costumer->id); // New costumer id
}
}
Я новичок в ORM DataMapper от CodeIgniter и немного потерялся в том, как я могу гарантировать сохранение человека ТОЛЬКО тогда, когда я успешно сохранил связанного клиента. Например, если я проверяю клиента status
, и он терпит неудачу, для сохранения этого клиента мне ранее приходилось хранить связанного с ним человека... Как я могу откатить нового человека, если я не могу сохранить клиента? (в реальном сценарии у меня есть таблицы persons
, individuals
, users
и costumers
, и мне нужно сохранить их только в случае успеха)
Как я могу использовать транзакции здесь? Да, я уже прочитал документацию об использовании транзакций, но я не могу понять, и я застрял на этом уже несколько часов. Заранее спасибо!
ОБНОВЛЕНИЕ
Я немного взломал свой контроллер, и теперь он, кажется, работает, есть ли лучший способ добиться этого?
Новый контроллер:
class Test extends CI_Controller {
public function index()
{
// Faking POST values
$_POST = array(
// Person info
'name' => 'Paulo Freitas',
'phone' => 'xxxxxxxxxx',
'email' => '[email protected]',
// Costumer info
'status' => 2
);
// Utility functions
function factory_from($class, $fields)
{
$CI =& get_instance();
$input = array();
foreach ($fields as $field) {
$input[$field] = $CI->input->post($field) ?: null;
}
$obj = new $class;
$obj->from_array($input);
return $obj;
}
function get_errors()
{
$errors = array();
foreach (func_get_args() as $obj) {
$errors += $obj->error->all;
}
return $errors;
}
// Initialize person
$person = factory_from('Person', array(
'name',
'phone',
'mobile',
'email'
));
// Initialize costumer
$costumer = factory_from('Costumer', array(
'status'
));
// Start transaction
$person->trans_begin();
if ($person->save()
&& $costumer->save($person)) {
// If we can save all data, commit!
$person->trans_commit();
// Dump new costumer id
var_dump($costumer->id);
} else {
// Otherwise, rollback all!
$person->trans_rollback();
// Dump all errors
var_dump(get_errors($person, $costumer));
}
}
}