Laravel:如何使用eloquent在DB中搜索给定的字符串?

时间:2015-04-13 15:57:18

标签: php mysql laravel laravel-4 eloquent

我想检索与搜索字符串匹配的数据,只要它不属于当前用户。

if($str_search && $str_search != '' )
{
  $mandate_list = Mandate::select(array('umrn','mandate_status', 'payment_type','currency','fixed_amount','max_amount','user_id','id','debtor_bank','creditor_bank','refusal_reason'))
                        ->orWhere('id', 'LIKE', '%'.$str_search.'%')
                        ->orWhere('umrn','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_status','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_date','LIKE','%'.$str_search.'%')
                        ->orWhere('payment_type','LIKE','%'.$str_search.'%')
                        ->orWhere('currency','LIKE','%'.$str_search.'%')
                        ->orWhere('fixed_amount','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_date','LIKE','%'.$str_search.'%')   
                        ->where('user_id', '<>', $current_user) 
                        ->orderBy('updated_at', 'desc')                            
                        ->get();

}

但是此查询显示所有记录(甚至属于当前用户)。 我怎么能解决这个问题。谢谢你的建议。

1 个答案:

答案 0 :(得分:2)

将所有orWhere分组到一个闭包中:

Mandate::select([.....])->where(function($query) use ($str_search)
{
    $columns = ['id', 'umrn', 'mandate_status', ...];

    foreach ($columns as $column)
    {
        $query->orWhere($column, 'LIKE', '%'.$str_search.'%');
    }
})
->where('user_id', '<>', $current_user) 
->orderBy('updated_at', 'desc')                            
->get();