-
Hello ! I have a request that create a simple order ( commands table ), then attach I the products throught a many to many (commands_products table ). Command model
Product model has these line for the relationship
Controller
I would like that my order ( Command.save() ) are not created when my products are not valid ( no product or invalid id ). But when this is the case, my command is created anyway. But on the product_command table not (and this is ok). How can I achieve this with a transaction ? I have look at the doc but nothing is working. I need a thing that not "save" the Command. Thanks a lot ! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Doesn't look like you're actually using the transaction. I think you're just one line away from having this working. const command = new Command();
command.useTransaction(trx); // <-- bind the transaction to your Command model instance
command.user_id = userId; https://docs.adonisjs.com/guides/database/transactions#using-transactions-with-lucid-models You shouldn't need to reapply the transaction here because Lucid will cascade the transaction to the related model from await created.related("products").attach(productData); https://docs.adonisjs.com/guides/database/transactions#persisting-relationships-inside-a-transaction |
Beta Was this translation helpful? Give feedback.
Doesn't look like you're actually using the transaction. I think you're just one line away from having this working.
https://docs.adonisjs.com/guides/database/transactions#using-transactions-with-lucid-models
You shouldn't need to reapply the transaction here because Lucid will cascade the transaction to the related model from
created
https://docs.adonisjs.com/guides/database/transactions#persisting-relationships-inside-a-transaction