MySQL8.0 の再帰クエリと Eloquent メモ
2022/07/07
with recursive
単独の Eloquent 内で with recursive を使用したい
- 100行ぐらいのSQLをLaravelのEloquent/Query Builderで頑張る - Qiita
- Laravel5で生のSQLを実行する方法
- MySQL — サブクエリに AS を付けないとエラーを起こす | Every derived table must have its own alias - Qiita
メソッド確認
- Illuminate\Database\Capsule\Manager | Laravel API
- query(): Illuminate\Database\Connection | Laravel API
- Builder: Illuminate\Database\Query\Builder | Laravel API
- selectRaw(): Illuminate\Database\Query\Builder | Laravel API
- select(): Illuminate\Database\Query\Builder | Laravel API
- raw(): Illuminate\Database\Connection | Laravel API
unionAll
- unionAll(): Illuminate\Database\Query\Builder | Laravel API
- MySQL の UNION / UNION ALL - MySQL の基礎 - MySQL 入門
外部パッケージ
もはや生PDOに回帰するか
whereIn()
最終的には
$hogeObjectsArray = $this->dbConnect->connection('hogera')
->select("
WITH recursive child(
depth,
id,
parent,
name
) AS (
SELECT 0,
id,
parent,
name
FROM hoge
WHERE id = {$foo}
UNION ALL
SELECT child.depth + 1,
hoge.id,
hoge.parent,
hoge.name
FROM hoge, child
WHERE hoge.parent = child.id
)
SELECT depth,
id,
parent,
name
FROM child
ORDER BY
depth
");
の形で取得てきた。 ->table($this->table) 等でテーブル指定せずにいきなり ->select() しているのがミソ。