首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP
TP3.2使用join查询实例以及注意事项
作者:小萝卜 2019-09-24 【 TP3.2 】 浏览 3341
简介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数据表
相关文章
- TP5 databackup拓展插件,实现数据库备份下载还原代码分享
- TP5 添加平铺文字水印,并设置文字之间的间距和文字的角度
- tp6多应用模式下渲染视图报错D:\PhpstormProjects\tp6\app\admin\view\.html
- TP6实现前后端分离的图片验证码,验证码怎么以接口形式返回
- TP5利用scp实现从a服务器转移文件到b服务器
- tp5 致命错误: Class 'think\route' not found
- SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attr_id' in 'where clause'
- TP6 TP5一键生成sitemap站点地图 代码分享
- TP5.1模型关联写法
- PayPal支付ThinkPHP3.2源代码
