視圖查詢(查詢建構器10)
視圖查詢可以實作不依賴資料庫視圖的多表查詢,並不需要資料庫支援視圖,是JOIN方法的建議替代方法,例如:
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語句類似於:
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方法的時候只需要使用欄位名稱而不需要加表名。
預設使用INNER join查詢,如果需要更改,可以使用:
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語句類似於:
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
可以使用別名:
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();
產生的SQL語句變成:
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
可以使用陣列的方式定義表名以及別名,例如:
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_user member INNER JOIN think_profile Profile ON Profile.user_id=member.id INNER JOIN think_socre Score ON Score.user_id=Profile.id WHERE Score.score > 80