ThinkPHP多表联合查询的常用方法
ThinkPHP中关联查询(即多表联合查询)可以使用table()方法或和join方法,具体使用如下例所示:
1、原生查询示例:
$Model=newModel(); $sql='selecta.id,a.title,b.contentfromthink_test1asa,think_test2asbwherea.id=b.id'.$map.'orderbya.id'.$sort.'limit'.$p->firstRow.','.$p->listRows; $voList=$Model->query($sql);
2、join()方法示例:
$user=newModel('user'); $list=$user->join('RIGHTJOINuser_profileONuser_stats.id=user_profile.typeid');
Thinkphp使用join联表查询的方法
$user=M('user'); $b_user=M('b_user'); $c_user=M('c_user'); $list=$user->alias('user')->where('user.user_type=1') ->join('b_userasbonb.b_userid=user.user_id') ->join('c_userasconc.c_userid=b.b_userid') ->order('b.user_time') ->select();
$user表的user_id等于$b_user表的b_userid;
$c_user表的c_userid等于$b_user表的b_userid;
3、table()方法示例:
$list=$user->table('user_statusstats,user_profileprofile')->where('stats.id=profile.typeid')->field('stats.idasid,stats.displayasdisplay,profile.titleastitle,profile.contentascontent')->order('stats.iddesc')->select();
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《smarty模板入门基础教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。