首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP
TP3.2使用join查询实例以及注意事项
作者:小萝卜 2019-09-24 【 TP3.2 】 浏览 2414
简介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定义常量报错:Use of undefined constant CONTROLLER_NAME - assumed 'CONTROLLER_NAME'
- tp5判断一张数据表是否存在
- TP6/Mysql源生查询当前月每天的数据统计
- tp6错误提示怎么不显示多少行了?
- tp6调试模式的开启与关闭
- tp5.0使用think-queue+redis实现消息队列简易教程
- SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attr_id' in 'where clause'
- TP5 databackup拓展插件,实现数据库备份下载还原代码分享
- TP5 关联模型使用(嵌套关联、动态排序以及隐藏字段)
- thinkphp6 使用 jwt 生成 token 中间件验证token