D
D
docxdocx2018-12-21 11:39:58
ORM
docxdocx, 2018-12-21 11:39:58

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):

  1. authors
  2. books
  3. pages
5c1ca6fdc2018868338913.jpeg
For them there are 3 models Author, Book, Page. I conditionally set up the links in the model classes like this:
Author -> hasMany(Book:class)

Book -> hasMany(Page::class)
Book -> belongsTo(Author:class)

Page -> belongsTo(Book:class)

The links are set up correctly, the selection from the database works as it should.
Doctrine ORM or Phalcon ORM has cascading relationship persistence. Conditionally it looks like this:
$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';
}

After that, records with the necessary relationships will be created in three tables. And all this will be saved in the database transaction. Those. save all or none.
In laravel models there is a push method, but that's not it. It does not store it in the transaction and does not store the links.
How to do this in laravel?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vism, 2018-12-21
@vism

It's just that in Laravel you need to start the transaction and commit it manually.
Welcome!

K
Konstantin B., 2018-12-21
@Kostik_1993

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 question

Ask a Question

731 491 924 answers to any question