LoginSignup
2
2

More than 5 years have passed since last update.

メソッドチェインにreduceを使う

Last updated at Posted at 2015-02-17

最近のPHP系ORMでもメソッドチェインなものが増えてきました。
そこで、例えば検索条件がテーブルに記録されていて、
そのレコードに沿ったwhere条件が連なっている場合を考えてみます。

そんなときは、こんな感じのコーディングもできますよ、という例です。
LaravelのEloquentを想定していますが、配列の場合はarray_reduceでいけますね。

<?php
$condition = SearchCondition::all();//ここに検索条件が記録されているとします
//field:フィールド名,value:検索値
$eloquent = new SomeModel; //\Illuminate\Database\Eloquent\Model継承のモデル
$result = $condition->reduce(function($carry, $item) {
        return $carry->where($item->field, '=', $item->value);
    }, $eloquent)->get();
2
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
2
2