问题描述:laravel where 条件拼接 Like出错,搜索不到要搜索的内容。

问题代码:

        // 作物
$crop_class_id = $request->crop_class_id;
if(!empty($crop_class_id)){
$where['crop_class_id'] = intval($crop_class_id);
}
// 标题
$title = $request->title;
if(!empty($title)){
// 这里的where获取不到like条件
$where['title'] = ['like', '%'.$title.'%'];
}

正确代码:

        // 作物
$crop_class_id = $request->crop_class_id;
if(!empty($crop_class_id)){
$where['crop_class_id'] = intval($crop_class_id);
}
// 标题
$title = $request->title;
if(!empty($title)){
// 如果拼接where条件存在比较符号,则不能指定key
$where[] = ['title', 'like', '%'.$title.'%'];
}

整体代码:

// 获取文章列表
// @url api/user/article?article_class_id=1&status=1&crop_class_id=1
public function index(Request $request)
{
$where = [];
// 分类
$article_class_id = $request->article_class_id;
if(!empty($article_class_id)){
$where['article_class_id'] = intval($article_class_id);
}
// 状态
$status = $request->status;
if(!empty($status)){
$where['status'] = intval($status);
}
// 作物
$crop_class_id = $request->crop_class_id;
if(!empty($crop_class_id)){
$where['crop_class_id'] = intval($crop_class_id);
}
// 标题
$title = $request->title;
if(!empty($title)){
$where[] = ['title', 'like', '%'.$title.'%'];
}
$limit = $request->input('limit');
$deviceRegionList = ArticleModel::where($where)->orderBy('id','desc')->with('user', 'article_class', 'crop_class')->paginate($limit)->toArray();
$returnData = [];
$returnData['msg'] = "查询成功";
$returnData['count'] = $deviceRegionList['total'];
$returnData['current_page'] = $deviceRegionList['current_page'];
$returnData['data'] = $deviceRegionList['data'];
return success($returnData);
}

参考连接:

  1. https://www.cnblogs.com/djwhome/p/9176338.html
05-11 22:02