首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP

TP3.2使用join查询实例以及注意事项

作者:小萝卜 2019-09-24 浏览 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)

文章评论

    高端网站建设