Laravel-5.6 'LIKE' in where select

折月煮酒 提交于 2019-12-11 15:17:43

问题


I use this query and i get a error :

 $description = $request->get('description');
        if (!empty($description)){
        $description_query = Transcationhistorique::where(['sender_id' => $user_id, "%$description%", 'LIKE','description'])
            ->orWhere('receiver_id', $user_id)->get();
        }else{
            $description_query  =  "" ;
        }

and this is the error that I get :

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from transcation_historique where (sender_id = 32 and 0 = %salaire% and 1 = LIKE and 2 = description) or receiver_id = 32)"

and this what really i want to run:

select * from `transcation_historique` where (`sender_id` = 32 and `description` = %salaire%) or `receiver_id` = 32)

回答1:


Try this,

$description_query = Transcationhistorique::where(
                         function($query) use ($user_id, $description){
                             return $query->where('sender_id', $user_id)
                                          ->where('description', 'like', '%' . $description .'%');

                         }
                     )
                     ->orWhere('receiver_id', $user_id)
                     ->get();



回答2:


It seems like your where query is not structured correctly. You should use the following structure if you want to use operators other than "=" Source

$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])

My suggestion is:

 $description = $request->get('description');
 if (!empty($description)){
     $description_query = Transcationhistorique::where([
            ['sender_id', '=', $user_id],
            ['description', 'LIKE', "%{$description}%"]
     ])
     ->orWhere('receiver_id', $user_id)->get();
 }else{
     $description_query  =  "" ;
 }




回答3:


Try this one:

Transcationhistorique::where('receiver_id', '=', $user_id)
        ->orWhere(function ($query) use ($user_id, $description) {
            $query->where('sender_id', '=', $user_id)->where('description', 'LIKE', "%".$description."%");
        })->get();



回答4:


You can use multiple where method as and. Can you try following codes?

    $description = $request->get('description');
    if (!empty($description)){
        $description_query = Transcationhistorique::where('sender_id', $user_id)
        ->where("description", 'LIKE','%' . $description . '%')
        ->orWhere('receiver_id', $user_id)->get();
    }else{
        $description_query  =  "" ;
    }


来源:https://stackoverflow.com/questions/54883894/laravel-5-6-like-in-where-select

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