6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】複数のカラムを指定してデータを取得する

Last updated at Posted at 2025-01-28

複数カラムの組み合わせを条件にデータ取得したい!!!

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のクエリが、対象のカラムとの対応がわかりやすくて好きです
6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?