首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP
TP3.2使用join查询实例以及注意事项
作者:小萝卜 2019-09-24 【 TP3.2 】 浏览 2838
简介TP3.2使用join查询实例以及注意事项,where条件只能用一个表的where两个表的where会报错,where中的字段要写表全称,不然会报错
TP3.2使用join查询实例以及注意事项
业务场景:
后台显示订单列表时想把会员的电话号码显示出来,但是订单表没有phone字段,user表和order表关联的字段是qid。这个时候我们使用join来实现上述需求。
order表查询条件:
$where['ueo56_order.datatype']=array('eq',1);
$where['ueo56_order.names']=array('like','%'.$names.'%');
$where['ueo56_order.ztype']=array('eq',$ztype);
$where['ueo56_order.stype']=array('eq',$stype);
错误条件,我想着既然order表的条件可以这么写,那我就再加个user表的条件应该也没问题吧
$where['ueo56_user.phone']=array('like','%'.$phone.'%');
结果用了上述user的条件之后sql语句跑不起来,这么坑爹?tp5都是可以给多表条件的吖!
没办法,改下条件,将user表的条件转到order表来,思路是这样:根据phone先查询user表获得会员的qid,然后在给order表qid的条件就可以了
//user表的条件
$where1['ueo56_user.phone']=array('like','%'.$phone.'%');
//根据phone查询user中的qid
$rd = M('user')->where($where1)->field('qid')->select();
//构造数据
$arr = array();
for ($i=0; $i < count($rd) ; $i++) {
$arr[$i] = $rd[$i]['qid'];
}
//构造order表的条件
$where['ueo56_order.qid'] = array('in',$arr);
最终的查询语句:
$product = M('ueo56_order');
$datalist = $product
->join('ueo56_user ON ueo56_order.qid = ueo56_user.qid')
->where($where)
->order("ueo56_order.id desc")
->field('ueo56_order.*,ueo56_user.qid as uqid,ueo56_user.phone as phone')
->limit(0,20)
->select();
这样就实现了我们的业务了,不过萝卜总觉得会有更好得办法来实现上面得业务,如果大伙有什么更简单的方法,一定要分享给萝卜哦!
很赞哦! (0)
上一篇:PHP数据类型转换
下一篇:tp5动态创建mysql数据表
相关文章
- TP6导入、导出Excel教程
- Swoole 结合TP5创建http服务
- tp5判断一张数据表是否存在
- tp5实现文件下载,并对下载的文件重命名
- TP5/TP6按驼峰命名了控制器和方法,运行时报错找不到模板文件
- ThinkPHP3.2和5.0的区别
- tp6表单验证提交之后报错Call to a member function set() on null
- tp5随机查询几条数据
- TP6使用Jwt验证token时报错Cannot pass parameter 3 by reference
- TP6阿里云OSS上传报SSL certificate problem:unable to get local issuer certificate