Answer the question
In order to leave comments, you need to log in
How to cascade save a model and its relationships in Laravel Eloquent ORM?
The question is about Eloquent ORM in Laravel 5.2. Let's say there are 3 tables (the structure is in the attached picture):
Author -> hasMany(Book:class)
Book -> hasMany(Page::class)
Book -> belongsTo(Author:class)
Page -> belongsTo(Book:class)
$firstPage = new Page();
$secondPage = new Page();
$book = new Book();
$book->setPages([$firstPage, $secondPage]);
$author = new Author();
$author->setBooks([$book]);
if ($author->save()) {
echo 'ok';
} else {
echo 'error';
}
Answer the question
In order to leave comments, you need to log in
It's just that in Laravel you need to start the transaction and commit it manually.
Welcome!
There are methods save, sync and a few more
. And there is only one transaction on Try cath. For example,
what is the point of a transaction if it is different for each request?))
Here is an example for you
$this->db->beginTransaction();
try {
$book = new Book;
$author = $request->user();
$author->books()->save($book);
$this->db->commit();
} catch (\Exception $e) {
$this->db->rollback();
return 'Error';
}
return 'Success';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question