LoginSignup
0
1

More than 1 year has passed since last update.

day12(?)の今日は集計関数を使う方法を見ていきます。

Doctrine

<?php

declare(strict_types=1);

use App\Entity\Author;
use App\Entity\Book;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;

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

/** @var EntityManagerInterface $entityManager */
$entityManager = require __DIR__.'/bootstrap.php';

$qb = $entityManager->getRepository(Book::class)->createQueryBuilder('b');
/** @var array<array{id: int, price_sum: int}> $rows */
$rows = $qb->leftJoin('b.author', 'a') // 第一引数はエンティティのフィールド名. エンティティ上でリレーションを定義してあればjoin条件は記述不要
    ->select('a.id, sum(b.price) as price_sum')
    ->groupBy('a.id')
    ->getQuery()
    ->getResult()
;

https://github.com/77web/doctrine-vs-eloquent/blob/686815966e6ac5471558229c4e77d23bbcd48b13/Doctrine/Usecase/filter_with_dql_function.php

Eloquent

<?php

declare(strict_types=1);

use App\Models\Author;
use Illuminate\Database\Eloquent\Collection;

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

/** @var Collection<Author> $authors1 */
$authors = Author::query()->leftJoin('books', 'books.author_id', 'authors.id')
    ->select('authors.id')
    ->selectRaw('sum(books.price) as price_sum')
    ->get()
;
// $authorsはattributeとしてidとprice_sumのみを持つAuthorモデルのインスタンス

https://github.com/77web/doctrine-vs-eloquent/blob/686815966e6ac5471558229c4e77d23bbcd48b13/Eloquent/Usecase/filter_with_sql_function.php

  • 各DBMSのSQL関数が selectRaw()whereRaw() などの xxxRaw() シリーズの中ではそのまま使えます。しかし、それゆえにDBMS間のポータビリティはいまいちです。
  • 取得できるのはAuthorモデルのインスタンスですが、idとprice_sumのみを持ち、他の値は持っていません。
0
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
0
1