How to realize save of different models within one transaction?



I have a model with a hasMany property. I edit properties of my model and several properties of each model in the hasMany.

What are the best solutions to realize a save function that saves everything in one transaction, so that the data in my database stays consistent if something fails while a request?




I know it is old topic but there are no answers. I am facing the same problem, what is considered best practice? I will use invoice as an example. Is it possible to have a model which will POST json like this bellow (with array of invoice details) and then I can deal with transaction on server side.

    "id": 1,
    "invoiceNumber": 123,
	    "id": 1,
	    "invoiceId": 1,
	    "productId": 1
    }, {
	    "id": 2,
	    "invoiceId": 1,
	    "productId": 2