dongpu1879 2018-02-26 17:11
浏览 80

将SQL转换为Eloquent Query Builder:Laravel5.5

How can I convert this SQL to Laravel5.5 Eloquent format

select * from 'arm_articles' where ('article_tag' like '%standard%' or 'article_topic' like '%standard%' or 'article_details' like '%standard%' or 'article_type' like '%standard%') and ( ('id' between 287 and 296) and 'article_active' = 1) order by 'id' desc

Please observer the braces in the SQL

This is the one i wrote that returns a different sql when i tested the output using ->toSql

$post= PostModel::where('article_tag','like','%'.$contributor_id.'%')->orWhere('article_topic','like','%'.$contributor_id.'%')->orWhere('article_details','like','%'.$contributor_id.'%')->orWhere('article_type','like','%'.$contributor_id.'%')->whereBetween('id', [$end, $start-1])->where('article_active',1)->orderBy('id', 'desc')->take(10)->get();

Find the SQL output from the query above

select * from 'arm_articles' where 'article_tag' like ? or 'article_topic' like ? or 'article_details' like ? or 'article_type' like ? and 'id' between ? and ? and 'article_active' = ? order by 'id' desc limit 10

This output looks like the needed SQL, but the different is the braces on the SQL. so one coin the Eloquent Query Builder to come out with the braces on the query ?

  • 写回答

2条回答 默认 最新

  • drvlf9739 2018-02-26 17:14
    关注

    Use the where() closure for parameter grouping:

    PostModel::where(function($q) use($contributor_id) {
            $q->where('article_tag', 'like', '%' . $contributor_id . '%')
              ->orWhere('article_topic', 'like', '%' . $contributor_id . '%')
              ->orWhere('article_details', 'like', '%' . $contributor_id . '%')
              ->orWhere('article_type', 'like', '%' . $contributor_id . '%');
        })
        ->whereBetween('id', [$end, $start - 1])
        ->where('article_active', 1)
        ->orderBy('id', 'desc')
        ->take(10)
        ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用