Home  >  Article  >  Backend Development  >  thinkphp3.2.3 连惯 写法

thinkphp3.2.3 连惯 写法

WBOY
WBOYOriginal
2016-06-06 20:10:511291browse

这句话换成 连贯操作 ,对新手来说 很难,望高手指点

<code>SELECT * FROM `hx_shop_period` WHERE ( id in ( SELECT DISTINCT  `pid` FROM `hx_shop_record` WHERE ( uid=101600 ) ORDER BY create_time desc  ) ) ORDER BY state asc,end_time desc LIMIT 0,20</code>

回复内容:

这句话换成 连贯操作 ,对新手来说 很难,望高手指点

<code>SELECT * FROM `hx_shop_period` WHERE ( id in ( SELECT DISTINCT  `pid` FROM `hx_shop_record` WHERE ( uid=101600 ) ORDER BY create_time desc  ) ) ORDER BY state asc,end_time desc LIMIT 0,20</code>

<code>//获取一个sql语句而不执行
$sub_query = M()->table('hx_shop_record')->distinct(true)->field('pid')->where(['uid'=>101600])->order('create_time DESC')->buildSql();
//使用子查询作为条件,获取结果
$rst = M()->table('hx_shop_period')->where('id in ' .$sub_query)->order('state ASC,end_time DESC')->limit(0,20)->select();</code>

在主流的数据库操作类库中都会有连贯操作的功能,其实并不麻烦,反而还非常好用.好处有:
1.不用记sql子语句的顺序
2.避免注入风险
3.封装了一些常用的方法,使用简单
4.多次拼装最后执行,可以组织复杂的语句

$res = $model->field('pid')->where('uid=101600')->order('create_time desc')->select(false);
$where['id'] = array('IN',$res)
$this->where($where)->order('state asc,end_time desc')->limit(0,20)->select();

好吧,其实我也没碰到这种,上面是看文档凭经验大概写的。
我直接推荐你用 $Model->query(原生SQL)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn