WEBOPIXEL

Laravelの配列(where in)でプリペアドステートメント使う方法

Laravelロゴ

Posted: 2022.09.17 / Category: PHP / Tag: 

Laravelで複雑なクエリとかは直接SQLを書くことがあると思います。
入力値やDBの値をクエリに組み込むときはプリペアドステートメントを使用しますが、配列(where in)で使おうとするとうまく動かなかったのでメモです。

Sponsored Link

postsテーブルからidが1,2,3のレコードを取得するクエリです。
固定で入れているのでこれは問題ないです。

DB::select("select * from posts where id in (1,2,3)");

変数を作りプリペアドステートメントで渡してみます。

$ids = '1,2,3';
DB::select("select * from posts where id in (?)", [$ids]);

結果は最初の1しか検索されないようです。

where inの部分は?を繋げることで想定通りの結果になります。

$ids = [1,2,3];
DB::select("select * from posts where id in (?, ? ,?)", $ids);

ただ配列の数は変動にしたいですね。ということでこんな感じです。

$ids = [1,2,5];
$placeholders = implode(',', array_fill(0, count($ids), '?'));
DB::select("select * from posts where id in ($placeholders)", $ids);