Yii2 Transaction

In this tutorial, I would like to show you how we can use transactions in YII2. A transaction is used to run a group of operations in the single process means a transaction is a unit of work.

Why should I use transaction?

In database we may need to perform add, update or delete operations on multiple tables while doing these operations on multiple tables if anything went wrong at one table few tables may be updated and few tables may not be updated. So there will be data inconsistency.Therefore, we want either a unit of work will be carried out completely or none. Hence the transaction is required to make it happen.

Here is the typical yii2 transaction template –

Yii2 Transaction Example

In below example, first We will create new user and then created user will assigned to the role. If two query will execute successfully, the commit function will work. But when first or second query will make errors, Nothing will not happen inside transaction and it will roll baked to original state.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

i want to enter two field with same name and other fields are distinct and i want to enter it as two entry in one table is it possible with yii2 transaction?

DMCA.com Protection Status
Would love your thoughts, please comment.x