day20(から5日遅れ)の今日はビューを利用する方法を見ていきます。
下記のような著者ごとの著作数を表すビューに対して、それぞれのORMでデータを読み出すやり方を示します。
CREATE VIEW `author_stat` as select authors.id, authors.name, count(books.id) as books_count from authors left join books on books.author_id = authors.id group by authors.id, authors.name;
Doctrine
Entity/AuthorStat.php
<?php declare(strict_types=1); namespace App\Entity; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(readOnly: true)] #[ORM\Table(name: 'author_stat')] class AuthorStat { #[ORM\Id] #[ORM\Column(type: 'integer')] private ?int $id; #[ORM\Column(type: 'string')] private ?string $name; #[ORM\Column(name: 'books_count', type: 'integer')] private ?int $booksCount; public function getId(): ?int { return $this->id; } public function setId(?int $id): void { $this->id = $id; } public function getName(): ?string { return $this->name; } public function setName(?string $name): void { $this->name = $name; } public function getBooksCount(): ?int { return $this->booksCount; } public function setBooksCount(?int $booksCount): void { $this->booksCount = $booksCount; } }
<?php declare(strict_types=1); use App\Entity\AuthorStat; use Doctrine\ORM\EntityManagerInterface; require __DIR__.'/../vendor/autoload.php'; /** @var EntityManagerInterface $entityManager */ $entityManager = require __DIR__.'/bootstrap.php'; /** @var AuthorStat[] $stats */ $stats = $entityManager->getRepository(AuthorStat::class)->findAll(); foreach ($stats as $stat) { echo sprintf('%s(%d)', $stat->getName(), $stat->getBooksCount()).PHP_EOL; }
- viewをreadonlyなEntityとして定義し、通常のEntityと同様にRepositoryやQueryBuilderを使ってレコードを取得できます。
Eloquent
Models/AuthorStat.php
<?php declare(strict_types=1); namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * App\Models\AuthorStat * * @property int $id * @property string $name * @property int $books_count */ class AuthorStat extends Model { public $table = 'author_stat'; }
<?php declare(strict_types=1); use App\Models\AuthorStat; require __DIR__.'/../vendor/autoload.php'; require __DIR__.'/bootstrap.php'; /** @var AuthorStat[] $stats */ $stats = AuthorStat::all(); foreach ($stats as $stat) { echo sprintf('%s(%d)', $stat->name, $stat->books_count).PHP_EOL; }
- viewをModelとして定義し、通常のModelと同様にModelのクエリ系メソッドを使ってレコードを取得できます。