視圖查詢
視(shi)(shi)圖查詢可以實現不依賴(lai)數(shu)據庫視(shi)(shi)圖的(de)多(duo)表查詢,并(bing)不需要數(shu)據庫支持視(shi)(shi)圖,例(li)如:
Db::view('User','id,name')
->view('Profile','truename,phone,email','Profile.user_id=User.id')
->view('Score','score','Score.user_id=Profile.id')
->where('score','>',80)
->select();
生成的SQL語句類似(si)于:
SELECT User.id,User.name,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User INNER JOIN think_profile Profile ON Profile.user_id=User.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
注意,視圖查詢無需調用
table和join方法,并且在調用where和order方法(fa)的時候(hou)只需(xu)要(yao)使用字段名而(er)不需(xu)要(yao)加(jia)表名。
默認(ren)使(shi)用(yong)INNER join查詢,如果需要更改(gai),可(ke)以使(shi)用(yong):
Db::view('User','id,name')
->view('Profile','truename,phone,email','Profile.user_id=User.id','LEFT')
->view('Score','score','Score.user_id=Profile.id','RIGHT')
->where('score','>',80)
->select();
生成的SQL語句類似(si)于:
SELECT User.id,User.name,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User LEFT JOIN think_profile Profile ON Profile.user_id=User.id RIGHT JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
可(ke)以使用別名:
Db::view('User',['id'=>'uid','name'=>'account'])
->view('Profile','truename,phone,email','Profile.user_id=User.id')
->view('Score','score','Score.user_id=Profile.id')
->where('score','>',80)
->select();
生成(cheng)的SQL語句變成(cheng):
SELECT User.id AS uid,User.name AS account,Profile.truename,Profile.phone,Profile.email,Score.score FROM think_user User INNER JOIN think_profile Profile ON Profile.user_id=User.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80
可以使用數組的(de)方(fang)式定義表名(ming)以及別名(ming),例如:
Db::view(['think_user'=>'member'],['id'=>'uid','name'=>'account'])
->view('Profile','truename,phone,email','Profile.user_id=member.id')
->view('Score','score','Score.user_id=Profile.id')
->where('score','>',80)
->select();
生成的SQL語句變成:
SELECT member.id AS uid,member.name AS account,Profile.truename,Profile.phone,Profile.email,Score.score FROM think
文檔最后更新時間:2018-04-26 09:52:31
未解決你的問題?請到「問答社區」反饋你遇到的問題
