複数カラムの組み合わせを条件にデータ取得したい!!!
foreachの中で一件ずつwhere繋げて条件指定して...なんてやってられん!ってことで、
whereRaw使った方法と、whereIn使った方法の2つで試したよ〜っていう個人的メモ。
whereRawで素のSQL書いちゃう
public function getItemList()
{
$itemParam = [
[1, 2, 3], //[a_id, b_id, c_id]
[4, 5, 6],
[7, 8, 9],
];
$query = DB::table('items');
$this->whereInItemParam($query, $itemParam);
$query->get();
}
public function whereInItemParam(Builder $query, ?array $itemParam): void
{
if (empty($itemParam)) {
$query->whereRaw('0');
return;
}
$placeholders = implode(',', array_fill(0, count($itemParam), '(?, ?, ?)'));
$query->whereRaw("(a_id, b_id, c_id) IN ($placeholders)", array_merge(...$itemParam));
}
結合してwhereIn
public function getItemList()
{
$itemParam = [
'1,2,3', //'a_id,b_id,c_id'
'4,5,6',
'7,8,9',
];
$query = DB::table('items');
$this->whereInItemParam($query, $itemParam);
$query->get();
}
public function whereInItemParam(Builder $query, ?array $itemParam): void
{
if (empty($itemParam)) {
$query->whereRaw('0');
return;
}
$query->whereIn(DB::raw("CONCAT(data_owner_shisetsu_id, ',', data_owner_id, ',', provide_service_id)"), $itemParam);
}
それぞれで発行されるクエリ
whereRaw
select * from `items` where (a_id, b_id, c_id) IN ((?, ?, ?),(?, ?, ?),(?, ?, ?));
whereIn
select * from `items` where CONCAT(a_id, ',', b_id, ',', c_id) in (?, ?, ?);
少しでもクエリ短くしたい...!!
みたいなこだわりのある場合は、whereIn使った方がプレースホルダ分短く済みますね
個人的にはwhereRowのクエリが、対象のカラムとの対応がわかりやすくて好きです