33
44class QuerySelect
55{
6- private $ table , $ alias , $ fields = array (), $ orders = array (), $ where = null ;
6+ private $ table , $ alias , $ fields = array (), $ orders = array (), $ where = null , $ joins = array () ;
77
88 public function __construct ($ table , $ alias = NULL )
99 {
@@ -41,25 +41,32 @@ public function get()
4141 $ table_alias = $ this ->alias ? $ this ->alias : $ this ->table ;
4242 foreach ($ this ->fields as $ ailas => $ field )
4343 {
44- $ fields [] = $ table_alias . ". " . $ field . " AS " . $ table_alias . ". " . $ ailas ;
44+ $ fields [] = $ table_alias . ". " . $ field . " AS " . $ table_alias . "__ " . $ ailas ;
4545 }
4646
47- if ($ fields )
47+ if (! $ fields )
4848 {
49- $ fields = implode (", " , $ fields );
50- }
51- else
52- {
53- $ fields = "* " ;
49+ $ fields [] = "$ table_alias.* " ;
50+
5451 }
5552
56- if ($ this ->alias )
53+ foreach ($ this ->joins as $ join )
5754 {
58- $ q = " SELECT $ fields FROM " . $ this -> table . " AS " . $ table_alias ;
55+ $ fields = array_merge ( $ fields, $ join [ " join " ]-> getFields ()) ;
5956 }
60- else
57+
58+ $ fields = implode (", " , $ fields );
59+
60+ $ q = "SELECT $ fields FROM " . $ this ->table . " AS " . $ table_alias ;
61+
62+ foreach ($ this ->joins as $ join )
6163 {
62- $ q = "SELECT $ fields FROM " . $ this ->table ;
64+ $ str = $ this ->getJoin ($ join ["join " ], $ join ["where " ]);
65+
66+ if ($ str )
67+ {
68+ $ q .= " " . $ str ;
69+ }
6370 }
6471
6572 $ wh = "" ;
@@ -82,4 +89,31 @@ public function get()
8289
8390 return $ q . $ wh . $ order . "; " ;
8491 }
92+
93+ public function join (Join $ join , Where $ wh = null )
94+ {
95+ $ this ->joins [] = array (
96+ "join " => $ join ,
97+ "where " => $ wh
98+ );
99+
100+ return $ this ;
101+ }
102+
103+ public function getJoin (Join $ join , Where $ wh = null )
104+ {
105+ if (is_null ($ wh ))
106+ {
107+ $ wh = new Where ("AND " );
108+ }
109+
110+ $ table_alias = $ this ->alias ? $ this ->alias : $ this ->table ;
111+ $ other_table_alias = $ join ->alias ? $ join ->alias : $ join ->table ;
112+
113+ $ wh ->add ($ table_alias . ". " . $ join ->primary_field , $ other_table_alias . ". " . $ join ->foreign_field , "= " , "" );
114+
115+ $ q = $ join ->join_type . " " . $ join ->table . " AS " . $ other_table_alias . " ON " . $ wh ->get ();
116+
117+ return $ q ;
118+ }
85119}
0 commit comments