当前位置:asp编程网>技术教程>Php教程>  正文

thinkphp5中,sql语句中既有and也有or的写法

2020-12-27 09:21:04   来源:www.aspbc.com   作者:wangsdong   浏览量:2646   收藏
在thinkphp的官方网站上介绍,and用->where(),or使用->whereor,如果一条sql语句中即有and也有or,怎么办?经过多次测试,找到了解决方法。
sql语句中即有and也有or有两种情况,大家注意一下写法
一、希望生成的sql代码如下:
select * from news where status = 1 or cat_id = 1 or id > 0
thinkphp5的写法是
$news = new News();
$news_data['status'] = array('eq',1);
$news_data['cat_id'] = array('eq',1);
$news_data['id'] = array('gt',0);
$list = $news
->whereor($news_data)
->select()

二、希望生成的sql代码如下:
select * from news where status = 1 or (cat_id = 1 or id > 0) //比上面多了一个括号
$news = new News();
$where1['status'] = array('eq',1);
$where2['cat_id'] = array('eq',1);
$where2['id'] = array('gt',0);
$list = $news
->where($where1)
->whereor($where2)
->select()

三、希望生成的sql代码如下:
select * from news where status = 1 and (cat_id = 1 or id > 0)
$news = new News();
$where1['status'] = array('eq',1);

$where2['cat_id'] = array('eq',1);
$where2['id'] = array('gt',0);
$list = $news
->where($where1)
->where(function($query)use($where){
   $query->whereor($where);
})
->select()

四、希望生成的sql代码如下:
select * from news where (status = 1 or isshow = 1 ) and (cat_id = 1 or id > 0)
$news = new News();
$where1['status'] = array('eq',1);
$where1['isshow'] = array('eq',1);

$where2['cat_id'] = array('eq',1);
$where2['id'] = array('gt',0);

$list = $news
->where(function($query)use($where1){
                $query->whereor($where1);
            })
->where(function($query)use($where2){
            $query->whereor($where2);
})
->select()

五、希望生成的sql代码如下:
select * from news where (status = 1 and is_show = 1 ) or (cat_id = 1 and id > 0)
$news = new News();
$where1['status'] = array('eq',1);
$where1['isshow'] = array('gt',1);

$where2['cat_id'] = array('eq',1);
$where2['id'] = array('gt',0);

$list = $news
->where(function($query)use($where1){
                $query->where($where1);
            })
->whereor(function($query)use($where2){
            $query->where($where2);
})

->select()


原创文章,转载请注明来源:www.aspbc.com,谢谢。


关于我们-广告合作-联系我们-积分规则-网站地图

Copyright(C)2013-2017版权所属asp编程网