LoginSignup
5
1

More than 1 year has passed since last update.

day1の今日はidとtitleという項目を持つbooksテーブルがあったとき、DoctrineとEloquentそれぞれでどう表すのか見てみます。
booksテーブルのmysql用のSQLは こちら

Doctrine

Entityクラスを定義します。

<?php

declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'books')]
class Book
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    #[ORM\GeneratedValue(strategy: 'AUTO')]
    private string $id;

    #[ORM\Column(type: 'string', length: 255, nullable: false)]
    private string $title;

    public function getId(): string
    {
        return $this->id;
    }

    public function setId(string $id): void
    {
        $this->id = $id;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }
}

https://github.com/77web/doctrine-vs-eloquent/blob/2f71adc7b61a1bff0214f9890395b986e55b7628/Doctrine/Entity/Book.php

  • 何も継承する必要はありません。必要に応じて何かを継承させたければ何を継承してもOK。interfaceを実装してもOK。
  • PHP8+のAttributeを使ってテーブルについての設定や各カラムについての設定をします。
  • データベース上に存在して、PHPから利用したいカラムはプロパティとして定義する必要があります。例ではprivateとしてgetter/setterメソッドを定義していますが、publicプロパティとして定義し、getter/setterを作らないこともできます。

Eloquent

Modelクラスを定義します。

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\Book
 *
 * @property int $id
 * @property string $title
 */
class Book extends Model
{
    public $fillable = [
        'title'
    ];
}

https://github.com/77web/doctrine-vs-eloquent/blob/2f71adc7b61a1bff0214f9890395b986e55b7628/Eloquent/Models/Book.php

  • Illuminate\Database\Eloquent\Model を継承します。
  • テーブルに存在するカラムについて記述する必要はありません。IDEで補完を効かせる目的で @property phpdocを書くことができます。
  • $fillable プロパティを設定しておくとEloquentの便利な機能を使ってデータを保存するときに役立ちます。
5
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
5
1