Laravel 5.0 Query Builder - Where with multiple parameters

无人久伴 提交于 2019-12-25 09:01:23

问题


I've a Laravel 5.0 project, that I need to implement the following logic

$var1= 'A';
$var2= 'B';
$var3= 50;
$data = DataModel::select('attr1','attr2')->where(function($q){
    $q->where('attr3','like','%'.$var1.'%');
    $q->where('attr4','like',$var2.'%');
    $q->where('attr5','=',$var3);
})->get();

The problem is for the "Where" function $var1, var2 and $var3 are undefined variables.

My Question is, How can I pass multiple parameters to the where function?


回答1:


Here, closure function passed in where argument. To inherit variables you have to use use keyword

For example function($q) use($var1, $var2, $var3){...

To learn more about closure function please check php manual.




回答2:


Try this

$var1= 'A';
$var2= 'B';
$var3= 50;
$data = DataModel::select('attr1','attr2')->where(function($q) use ($var1, $var2, $var3) {
    $q->where('attr3','like','%'.$var1.'%')
        ->orWhere('attr4','like',$var2.'%')
        ->orWhere('attr5','=',$var3);
})->get();


来源:https://stackoverflow.com/questions/40357023/laravel-5-0-query-builder-where-with-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!