首页 > 技术文章 > thinkphp关联查询(多表查询)

yelp 2013-12-20 15:27 原文

1、Table方法:定义要操作的数据表名称,可以动态改变当前操作的数据表名称,需要写数据表的全名,包含前缀,可以使用别名,

例如:

$Model->Table('think_user user')->where('status>1')->select();
$Model->table('think_blog blog,think_type type')->where('blog.typeid=type.id')->field('blog.id as id,blog.title,blog.content,type.typename as type')->order('blog.id desc')->limit(5)->select();

Table方法的参数支持字符串和数组,数组方式的用法:

$Model->Table(array('think_user'=>'user','think_group'=>'group'))->where('status>1')->select();

使用数组方式定义的优势是可以避免因为表名和关键字冲突而出错的情况。
注:如果不定义table方法,默认会自动获取当前模型对应或者定义的数据表。
2、Join方法:查询Join支持,Join方法的参数支持字符串和数组,并且join方法是连贯操作中唯一可以多次调用的方法。
例如:

$Model->join('work ON artist.id = work.artist_id')->join('card ON artist.card_id = card.id')->select();  
//Left Join
$Model->table('user U')->join('news N on U.id=N.cid')->field('U.*,N.*')->order('id desc')->limit('8')->findall();

 

默认采用LEFT JOIN 方式,如果需要用其他的JOIN方式,可以改成

$Model->join('RIGHT JOIN work ON artist.id = work.artist_id')->select();//Right Join
$Model->table('user U')->join(array('right','news N on U.id=N.cid'))->field('U.*,N.*')->order('id desc')->limit('8')->findall();

如果join方法的参数用数组的话,只能使用一次join方法,并且不能和字符串方式混合使用。

$Model->join(array(' work ON artist.id = work.artist_id','card ON artist.card_id = card.id'))->select();

$Model->join(array(' work ON artist.id = work.artist_id','card ON artist.card_id = card.id'))->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);

 

 

 

推荐阅读