thinkphp 关联查询sql语句多种方法

发布时间:2020-10-28编辑:脚本学堂
thinkphp 关联查询实现代码,thinkphp实现多表关联查询,包括table、join与原生查询与多表查询等方法,本文举了一些这方面的例子,供大家学习参考。

thinkphp 关联查询用法

在thinkphp中关联查询(多表查询)可以使用 table() 方法或和join方法。

实例代码,如下:

1、table() 关联查询
 

复制代码 代码示例:
$list = $user->table('user_status stats, user_profile profile')->where('stats.id = profile.typeid')->field('stats.id as id, stats.display as display, profile.title as title,profile.content as content')->order('stats.id desc' )->select();

2、join() 关联查询
 

复制代码 代码示例:
$user = new Model('user'); 
$list = $user->join('RIGHT JOIN user_profile ON user_stats.id = user_profile.typeid' )->select();

3、原生查询
 

复制代码 代码示例:
$Model = new Model(); 
$sql = 'select a.id,a.title,b.content from think_test1 as a, think_test2 as b where a.id=b.id '.$map.' order by a.id '.$sort.' limit '.$p->firstRow.','.$p->listRows; $voList = $Model->query($sql);

4、多表查询
 

复制代码 代码示例:
$Model->field('user.name,role.title')->table('think_user user,think_role role')->limit(10)->select();
或:
$Model->field('user.name,role.title')->table(array('think_user'=>'user','think_role'=>'role'))->limit(10)->select();

以上通过实例介绍了thinkphp关联查询的几种方法,希望对大家学习thinkphp有一定帮助。