Please Help! I'm can't finish transaction success.
When I passed in form wrong data and send the form, my transaction start, the first table skipped, because of failed validation, but the transaction continue working and some data insert in two and three tables. Why it's happening?
I'm validating data in the model, here my code
namespace App\Models;
use CodeIgniter\Model;
class Users extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDelete = false;
protected $protectFields = true;
protected $allowedFields = [
'full_name', 'phone_user', 'inn_user', 'hospital_code', 'check_priz', 'winner', 'banned',
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'full_name' => 'required|min_length[3]|max_length[255]',
'phone_user' => 'required|is_unique[users.phone_user]|min_length[11]|max_length[11]|regex_match[/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/]|numeric',
'inn_user' => 'required|numeric|is_unique[users.inn_user]|min_length[12]|max_length[12]',
'hospital_code' => 'integer|max_length[5]'
];
protected $validationMessages = [];
protected $skipValidation = false;
}
And this my function with the transaction
public function addNewUserAndCode($data)
{
$userModel = new UserModel;
$CodeModel = new CodeModel;
$CodeUserModel = new CodeUserModel;
$db = \Config\Database::connect();
$db->transBegin();
//create user
$id = $userModel->insert($data);
//add code to user
$promoCodeUserModel->insert([
'user_id' => $id,
'code' => $data['code']
]);
//check used code
$promoCodeModel->update($data['code'], ['used' => 1]);
$db->transComplete();
if ($db->transStatus() === FALSE) {
$db->transRollback();
log_message('debug', 'fail transaction');
return $this->fail('Failed add user.', 400);
} else {
$db->transCommit();
log_message('debug', 'success transaction');
}
}
Sorry for my English. :) Thank you very much!)