thinkphp關聯查詢(多表查詢)


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);

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM