THINKPHP 中关联查询(多表查询)
Posted MichaelYUE
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了THINKPHP 中关联查询(多表查询)相关的知识,希望对你有一定的参考价值。
THINKphp 中关联查询(多表查询)可以使用 table() 方法或和join方法,请看示例:
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();
$Model->Table(array(‘think_user‘=>‘user‘,‘think_group‘=>‘group‘))
->where(‘status>1‘)
->select();
$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();
$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();
$Model->join(array(‘ work ON artist.id = work.artist_id‘, ‘card ON artist.card_id = card.id‘))
->select()
echo $Model->getLastSql(); //打印一下SQL语句,查看一下
例2:
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.1、join()2表查询
$user = new Model(‘user‘);
$list = $user->join(‘RIGHT JOIN user_profile ON user_stats.id = user_profile.typeid‘ );
2.2、join() 多表查询
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);
以上是关于THINKPHP 中关联查询(多表查询)的主要内容,如果未能解决你的问题,请参考以下文章