Laravel where条件拼接,数组拼接where条件

问题描述: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
posted @   夏秋初  阅读(8151)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示