一种更有效的查询关系的方法

时间:2015-03-09 21:14:04

标签: laravel

我正在对表(产品)构建查询。

产品有一个外键,wrapper_id,

反过来,每个包装器都有一个外键wrapper_classification_id。

这部分查询需要根据可能作为输入参数传递的wrapper_classification_id数组修改搜索。

这就是我正在做的事情:

     // $query is already being built from above this line....
     // wrapper_classification_id in input is an array

    if (Input::get('wrapper_classification_id'))
    {
        $wrappers = Wrapper::whereIn('wrapper_classification_id', Input::get('wrapper_classification_id'))->get();
        $wrapperArray = [];
        foreach($wrappers as $wrapper) {
            $wrapperArray[] = $wrapper->id;
        }
        $query->whereIn('wrapper_id', $wrapperArray );
    }

是否有更有效的方法来处理这种情况,您在查询关系中的值?

提前致谢, 富

2 个答案:

答案 0 :(得分:1)

$query->whereIn(
    'wrapper_id', 
    DB::raw(
        Wrapper::whereIn(
            'wrapper_classification_id', 
            Input::get('wrapper_classification_id')
        )->toSql()
    )
);

或者,尝试加入。

$query->join('wrapper AS w', 'w.wrapper_classification_id', 'IN', Input::get('wrapper_classification_id'))
    ->whereIn('product.wrapper_id', 'w.id');

不确定该确切代码是否可行。

答案 1 :(得分:1)

假设产品型号具有wrapper关系:

if (Input::has('wrapper_classification_id'))
{
    $query->whereHas('wrapper', function($q){
        $q->whereIn('wrapper_classification_id', Input::get('wrapper_classification_id'));
    });
}