LoginSignup
7
1

More than 1 year has passed since last update.

day2の今日は、day1で定義したレコードを表すクラス(Entity, Model)を使って、Doctrine・Eloquentそれぞれのレコードを1件追加(登録, insert)する方法を見ていきます。

Doctrine

<?php

declare(strict_types=1);

use App\Entity\Book;
use Doctrine\ORM\EntityManagerInterface;

require __DIR__.'/../vendor/autoload.php';

$newBook = new Book();
$newBook->setTitle('ちょうぜつソフトウェア設計入門');

/** @var EntityManagerInterface $entityManager */
$entityManager = require __DIR__.'/bootstrap.php';
$entityManager->persist($newBook);
$entityManager->flush();

https://github.com/77web/doctrine-vs-eloquent/blob/dd6ebe256dcc08507ad00954059ed59306394c3a/Doctrine/Usecase/create_new_record.php

  • Bookエンティティのインスタンスを新しく作ります。
  • Bookのインスタンスのtitleプロパティに書名をセットします。(setterを利用)
  • BookのインスタンスをEntityManagerのpersist()に渡します。
  • EntityManagerのflush()を呼びます。
  • もしデータベースへの接続がない状態で実行すると、 $entityManager->flush() の時点でエラーになります。

Eloquent

<?php

declare(strict_types=1);

use App\Models\Book;

$newBook = new Book();
$newBook->title = 'ちょうぜつソフトウェア設計入門';
$newBook->save();

https://github.com/77web/doctrine-vs-eloquent/blob/dd6ebe256dcc08507ad00954059ed59306394c3a/Eloquent/Usecase/create_new_record.php

  • Bookモデルのインスタンスを新しく作ります。
  • Bookのインスタンスのtitleプロパティに書名をセットします。
  • Bookのインスタンスのsave()メソッドを呼び出します。
  • もしデータベースへの接続のない状態で実行すると、save()の時点でエラーになります。
7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1