Welcome Guest, Not a member yet? Register   Sign In
Transaction with multiple models
#1
Question 

Hello, this is for a to-do project.
I will insert data into two models, and I want to use a transaction. Where and how should this transaction be managed? I was thinking of doing it in the service layer, but I wanted to ask. If you have any other suggestions, please let me know.

Model Names:
  • tasks (id, title, description, status, created_at, updated_at)
  • task_user (id, user_id, task_id)
Thank you for your time and assistance.
Reply
#2

This may help you out for doing it in a Controller etc.

Struggling with transaction using multiple models
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Hello @kuzeyybora i implemented with service layer and it looked like this:

PHP Code:
class SettingsService
{
    private BaseConnection $db;
    private UserModel $userModel;
    private BirdSquadModel $birdSquadModel;
    private PersonModel $personModel;
    public function __construct(?BaseConnection $db null)
    {
        $this->db $db ?? db_connect();
        $this->userModel model(UserModel::class, true$this->db);
        $this->birdSquadModel model(BirdSquadModel::class, true$this->db);
        $this->personModel model(PersonModel::class, true$this->db);
    }
    public function saveOrUpdate(int $userId, array $data): void
    
{
        $this->db->transStart();
        $userEntity $this->userModel->find($userId);
            
        
if ($userEntity->birdSquadId && $userEntity->personId) {
            $this->birdSquadModel->update($userEntity->birdSquadId, ['name' => $data['birdSquadName']]);
            $this->personModel->update($userEntity->personId, ['name' => $data['personName']]);
        } else {
            $birdSquadId $this->birdSquadModel->insert(['name' => $data['birdSquadName']]);
            $personId $this->personModel->insert(['name' => $data['personName']]);
            
            
if ($birdSquadId && $personId 0) {
                $this->userModel->update($userEntity->id, ['bird_squad_id' => $birdSquadId'person_id' => $personId]);
            }
        }
        $this->db->transComplete();
    }


Does this implementation make sense to you?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB