Finders

Version 8 (Kien La, 2010-06-19 05:54 PM)

1 3 Kien La
h2. Finders
2 3 Kien La
3 2 Kien La
*(#topic-list) "Single record result":/projects/main/wiki/Finders#single-record-result
4 1
* "Multiple records result":/projects/main/wiki/Finders#multiple-records-result
5 4 Kien La
* "Finder options":/projects/main/wiki/Finders#finder-options
6 4 Kien La
* "Conditions":/projects/main/wiki/Finders#conditions
7 4 Kien La
* "Limit & Offset":/projects/main/wiki/Finders#limit-offset
8 4 Kien La
* "Order":/projects/main/wiki/Finders#order
9 4 Kien La
* "Select":/projects/main/wiki/Finders#select
10 4 Kien La
* "From":/projects/main/wiki/Finders#from
11 5 Kien La
* "Group":/projects/main/wiki/Finders#group
12 5 Kien La
* "Having":/projects/main/wiki/Finders#having
13 4 Kien La
* "Read only":/projects/main/wiki/Finders#read-only
14 4 Kien La
* "Dynamic finders":/projects/main/wiki/Finders#dynamic-finders
15 4 Kien La
* "Joins":/projects/main/wiki/Finders#joins
16 4 Kien La
* "Find by custom SQL":/projects/main/wiki/Finders#find-by-custom-sql
17 1
18 1
ActiveRecord supports a number of methods by which you can find records such as: via primary key, dynamic field name finders. It has the ability to fetch all the records in a table with a simple call, or you can make use of options like order, limit, select, and group.
19 1
20 6 Kien La
There are essentially two groups of finders you will be working with: "a single record result":/projects/main/wiki/Finders#single-record-result and "multiple records result":/projects/main/wiki/Finders#multiple-records-result. Sometimes there will be little transparency for the method calls, meaning you may use the same method to get either one, but you will pass an option to that method to signify which type of result you will fetch.
21 1
22 7 Kien La
All methods used to fetch records from your database will go through *Model::find()*, with one exception, custom sql can be passed to "Model::find_by_sql()":/projects/main/wiki/Finders#find-by-custom-sql. In all cases, the finder methods in ActiveRecord are statically invoked. This means you will always use the following type of syntax.
23 1
24 1
<pre class="code"><code class="php">
25 1
class Book extends ActiveRecord\Model {}
26 1
 
27 1
Book::find('all');
28 1
Book::find('last');
29 1
Book::first();
30 1
Book::last();
31 1
Book::all();
32 1
</code></pre>
33 1
 
34 2 Kien La
h4(#single-record-result). Single record result
35 1
36 1
Whenever you invoke a method which produces a single result, that method will return an instance of your model class. There are 3 different ways to fetch a single record result. We'll start with one of the most basic forms.
37 1
38 1
h4. Find by primary key
39 1
40 6 Kien La
You can grab a record by passing a primary key to the find method. You may pass an "options array":/projects/main/wiki/Finders#finder-options as the second argument for creating specific queries. If no record is found, a RecordNotFound exception will be thrown.
41 1
42 1
<pre class="code"><code class="php">
43 1
# Grab the book with the primary key of 2
44 1
Book::find(2);
45 1
# sql => SELECT * FROM `books` WHERE id = 2
46 1
</code></pre>
47 1
 
48 1
h4. Find first
49 1
50 1
You can get the first record back from your database two ways. If you do not pass conditions as the second argument, then this method will fetch all the results from your database, but will only return the very first result back to you. Null will be returned if no records are found.
51 1
52 1
<pre class="code"><code class="php">
53 1
# Grab all books, but only return the first result back as your model object.
54 1
$book = Book::first();
55 1
echo "the first id is: {$book->id}" # => the first id is: 1
56 1
# sql => SELECT * FROM `books`
57 1
58 1
# this produces the same sql/result as above
59 1
Book::find('first');
60 1
</code></pre>
61 1
 
62 1
h4. Find last
63 1
64 1
If you haven't yet fallen asleep reading this guide, you should've guessed this is the same as "find first", except that it will return the last result. Null will be returned if no records are found.
65 1
66 1
<pre class="code"><code class="php">
67 1
# Grab all books, but only return the last result back as your model object.
68 1
$book = Book::last();
69 1
echo "the last id is: {$book->id}" # => the last id is: 32
70 1
# sql => SELECT * FROM `books`
71 1
72 1
# this produces the same sql/result as above
73 1
Book::find('last');
74 1
</code></pre>
75 1
 
76 2 Kien La
h4(#multiple-records-result). Multiple records result
77 1
78 1
This type of result will always return an array of model objects. If your table holds no records, or your query yields no results, then an empty array will be given.
79 1
80 1
h4. Find by primary key
81 1
82 6 Kien La
Just like the single record result for find by primary key, you can pass an array to the find method for multiple primary keys. Again, you may pass an "options array":/projects/main/wiki/Finders#finder-options as the last argument for creating specific queries. Every key which you use as an argument must produce a corresponding record, otherwise, a RecordNotFound exception will be thrown.
83 1
84 1
<pre class="code"><code class="php">
85 1
# Grab books with the primary key of 2 or 3
86 1
Book::find(2,3);
87 1
# sql => SELECT * FROM `books` WHERE id IN (2,3)
88 1
89 1
# same as above
90 1
Book::find(array(2,3));
91 1
</code></pre>
92 1
 
93 1
h4. Find all
94 1
95 6 Kien La
There are 2 more ways which you can use to get multiple records back from your database. They use different methods; however, they are basically the same thing. If you do not pass an "options array":/projects/main/wiki/Finders#finder-options, then it will fetch all records.
96 1
97 1
<pre class="code"><code class="php">
98 1
# Grab all books from the database
99 1
Book::all();
100 1
# sql => SELECT * FROM `books`
101 1
102 1
# same as above
103 1
Book::find('all');
104 1
</code></pre>
105 1
 
106 1
Here we pass some options to the same method so that we don't fetch *every* record.
107 1
108 1
<pre class="code"><code class="php">
109 1
$options = array('limit' => 2);
110 1
Book::all($options);
111 1
# sql => SELECT * FROM `books` LIMIT 0,2
112 1
113 1
# same as above
114 1
Book::find('all', $options);
115 1
</code></pre>
116 1
 
117 4 Kien La
h4(#finder-options). Finder options
118 1
119 1
There are a number of options available to pass to one of the finder methods for granularity. Let's start with one of the most important options: conditions.
120 1
121 4 Kien La
h4(#conditions). Conditions
122 1
123 1
This is the "WHERE" of a SQL statement. By creating conditions, ActiveRecord will parse them into a corresponding "WHERE" SQL statement to filter out your results. Conditions can be extremely simple by only supplying a string. They can also be as complex as you'd like by creating a conditions string that uses ? marks as placeholders for values. Let's start with a simple example of a conditions string.
124 1
125 1
<pre class="code"><code class="php">
126 1
# fetch all the cheap books!
127 1
Book::all(array('conditions' => 'price < 15.00'));
128 1
# sql => SELECT * FROM `books` WHERE price < 15.00
129 1
130 1
# fetch all books that have "war" somewhere in the title
131 1
Book::find(array('conditions' => "title LIKE '%war%'"));
132 1
# sql => SELECT * FROM `books` WHERE title LIKE '%war%'
133 1
</code></pre>
134 1
 
135 1
As stated, you can use *?* marks as placeholders for values which ActiveRecord will replace with your supplied values. The benefit of using this process is that ActiveRecord will escape your string in the backend with your database's native function to prevent SQL injection.
136 1
137 1
<pre class="code"><code class="php">
138 1
# fetch all the cheap books!
139 1
Book::all(array('conditions' => array('price < ?', 15.00)));
140 1
# sql => SELECT * FROM `books` WHERE price < 15.00
141 1
142 1
# fetch all lousy romance novels
143 1
Book::find('all', array('conditions' => array('genre = ?', 'Romance')));
144 1
# sql => SELECT * FROM `books` WHERE genre = 'Romance'
145 1
146 1
# fetch all books with these authors
147 1
Book::find('all', array('conditions' => array('author_id in (?)', array(1,2,3))));
148 1
# sql => SELECT * FROM `books` WHERE author_id in (1,2,3)
149 1
150 1
# fetch all lousy romance novels which are cheap
151 1
Book::all(array('conditions' => array('genre = ? AND price < ?', 'Romance', 15.00)));
152 1
# sql => SELECT * FROM `books` WHERE genre = 'Romance' AND price < 15.00
153 1
</code></pre>
154 1
 
155 1
Here is a more complicated example. Again, the first index of the conditions array are the condition strings. The values in the array after that are the values which replace their corresponding ? marks.
156 1
157 1
<pre class="code"><code class="php">
158 1
# fetch all cheap books by these authors
159 1
$cond =array('conditions'=>array('author_id in(?) AND price < ?', array(1,2,3), 15.00));
160 1
Book::all($cond);
161 1
# sql => SELECT * FROM `books` WHERE author_id in(1,2,3) AND price < 15.00
162 1
</code></pre>
163 1
 
164 4 Kien La
h4(#limit-offset). Limit & Offset
165 1
166 1
This one should be fairly obvious. A limit option will produce a SQL limit clause for supported databases. It can be used in conjunction with the *offset* option.
167 1
168 1
<pre class="code"><code class="php">
169 1
# fetch all but limit to 10 total books
170 1
Book::find('all', array('limit' => 10));
171 1
# sql => SELECT * FROM `books` LIMIT 0,10
172 1
173 1
# fetch all but limit to 10 total books starting at the 6th book
174 1
Book::find('all', array('limit' => 10, 'offset' => 5));
175 1
# sql => SELECT * FROM `books` LIMIT 5,10
176 1
</code></pre>
177 1
 
178 4 Kien La
h4(#order). Order
179 1
180 1
Produces an ORDERY BY SQL clause.
181 1
182 1
<pre class="code"><code class="php">
183 1
# order all books by title desc
184 1
Book::find('all', array('order' => 'title desc'));
185 1
# sql => SELECT * FROM `books` ORDER BY title desc
186 1
187 1
# order by most expensive and title
188 1
Book::find('all', array('order' => 'price desc, title asc'));
189 1
# sql => SELECT * FROM `books` ORDER BY price desc, title asc
190 1
</code></pre>
191 1
 
192 4 Kien La
h4(#select). Select
193 1
194 6 Kien La
Passing a select key in your "options array":/projects/main/wiki/Finders#finder-options will allow you to specify which columns you want back from the database. This is helpful when you have a table with too many columns, but you might only want 3 columns back for 50 records. It is also helpful when used with a group statement.
195 1
196 1
<pre class="code"><code class="php">
197 1
# fetch all books, but only the id and title columns
198 1
Book::find('all', array('select' => 'id, title'));
199 1
# sql => SELECT id, title FROM `books`
200 1
201 1
# custom sql to feed some report
202 1
Book::find('all', array('select' => 'avg(price) as avg_price, avg(tax) as avg_tax'));
203 1
# sql => SELECT avg(price) as avg_price, avg(tax) as avg_tax FROM `books` LIMIT 5,10
204 1
</code></pre>
205 1
 
206 4 Kien La
h4(#from). From
207 1
208 6 Kien La
This designates the table you are selecting from. This can come in handy if you do a "join":/projects/main/wiki/Finders#joins or require finer control.
209 1
210 1
<pre class="code"><code class="php">
211 1
# fetch the first book by aliasing the table name
212 1
Book::first(array('select'=> 'b.*', 'from' => 'books as b'));
213 1
# sql => SELECT b.* FROM books as b LIMIT 0,1
214 1
</code></pre>
215 1
 
216 4 Kien La
h4(#group). Group
217 1
218 1
Generate a GROUP BY clause.
219 1
220 1
<pre class="code"><code class="php">
221 1
# group all books by prices
222 1
Book::all(array('group' => 'price'));
223 1
# sql => SELECT * FROM `books` GROUP BY price
224 1
</code></pre>
225 1
 
226 4 Kien La
h4(#having). Having
227 1
228 1
Generate a HAVING clause to add conditions to your GROUP BY.
229 1
230 1
<pre class="code"><code class="php">
231 1
# group all books by prices greater than $45
232 1
Book::all(array('group' => 'price', 'having' => 'price > 45.00'));
233 1
# sql => SELECT * FROM `books` GROUP BY price HAVING price > 45.00
234 1
</code></pre>
235 1
 
236 4 Kien La
h4(#read-only). Read only
237 1
238 1
Readonly models are just that: readonly. If you try to save a readonly model, then a ReadOnlyException will be thrown.
239 1
240 1
<pre class="code"><code class="php">
241 1
# specify the object is readonly and cannot be saved
242 1
$book = Book::first(array('readonly' => true));
243 1
 
244 1
try {
245 1
  $book->save();
246 1
} catch (ActiveRecord\ReadOnlyException $e) {
247 1
  echo $e->getMessage();
248 1
  # => Book::save() cannot be invoked because this model is set to read only
249 1
}
250 1
</code></pre>
251 1
 
252 4 Kien La
h4(#dynamic-finders). Dynamic finders
253 1
254 8 Kien La
These offer a quick and easy way to construct conditions without having to pass in a bloated array option. This option makes use of PHP 5.3's "late static binding":http://www.php.net/lsb combined with "__callStatic()":http://www.php.net/__callstatic allowing you to invoke undefined static methods on your model. You can either use YourModel::find_by which returns a "single record result":/projects/main/wiki/Finders#single-record-result and YourModel::find_all_by returns "multiple records result":/projects/main/wiki/Finders#multiple-records-result. All you have to do is add an underscore and another field name after either of those two methods. Let's take a look.
255 1
256 1
<pre class="code"><code class="php">
257 1
# find a single book by the title of War and Peace
258 1
$book = Book::find_by_title('War and Peace');
259 1
#sql => SELECT * FROM `books` WHERE title = 'War and Peace'
260 1
261 1
# find all discounted books
262 1
$book = Book::find_all_by_discounted(1);
263 1
#sql => SELECT * FROM `books` WHERE discounted = 1
264 1
265 1
# find all discounted books by given author
266 1
$book = Book::find_all_by_discounted_and_author_id(1, 5);
267 1
#sql => SELECT * FROM `books` WHERE discounted = 1 AND author_id = 5
268 1
269 1
# find all discounted books or those which cost 5 bux
270 1
$book = Book::find_by_discounted_or_price(1, 5.00);
271 1
#sql => SELECT * FROM `books` WHERE discounted = 1 OR price = 5.00
272 1
</code></pre>
273 1
 
274 4 Kien La
h4(#joins). Joins
275 1
276 6 Kien La
A join option may be passed to specify SQL JOINS. There are two ways to produce a JOIN. You may pass custom SQL to perform a join as a simple string. By default, the joins option will not "select":/projects/main/wiki/Finders#select the attributes from the joined table; instead, it will only select the attributes from your model's table. You can pass a select option to specify the fields.
277 1
278 1
<pre class="code"><code class="php">
279 1
# fetch all books joining their corresponding authors
280 1
$join = 'LEFT JOIN authors a ON(books.author_id = a.author_id)';
281 1
$book = Book::all(array('joins' => $join));
282 1
# sql => SELECT `books`.* FROM `books`
283 1
#	  LEFT JOIN authors a ON(books.author_id = a.author_id)
284 1
</code></pre>
285 1
 
286 6 Kien La
Or, you may specify a join via an "associated":/projects/main/wiki/Associations model.
287 1
288 1
<pre class="code"><code class="php">
289 1
class Book extends ActiveRecord\Model
290 1
{
291 1
  static $belongs_to = array(array('author'),array('publisher'));
292 1
}
293 1
 
294 1
# fetch all books joining their corresponding author
295 1
$book = Book::all(array('joins' => array('author')));
296 1
# sql => SELECT `books`.* FROM `books`
297 1
#	  INNER JOIN `authors` ON(`books`.author_id = `authors`.id)
298 1
299 1
# here's a compound join
300 1
$book = Book::all(array('joins' => array('author', 'publisher')));
301 1
# sql => SELECT `books`.* FROM `books`
302 1
#	  INNER JOIN `authors` ON(`books`.author_id = `authors`.id)
303 1
#         INNER JOIN `publishers` ON(`books`.publisher_id = `publishers`.id)
304 1
</code></pre>
305 1
 
306 1
Joins can be combined with strings and associated models.
307 1
308 1
<pre class="code"><code class="php">
309 1
class Book extends ActiveRecord\Model
310 1
{
311 1
  static $belongs_to = array(array('publisher'));
312 1
}
313 1
 
314 1
$join = 'LEFT JOIN authors a ON(books.author_id = a.author_id)';
315 1
# here we use our $join string and the association publisher
316 1
$book = Book::all(array('joins' => $join, 'publisher'));
317 1
# sql => SELECT `books`.* FROM `books`
318 1
#	  LEFT JOIN authors a ON(books.author_id = a.author_id)
319 1
#         INNER JOIN `publishers` ON(`books`.publisher_id = `publishers`.id)
320 1
</code></pre>
321 1
 
322 4 Kien La
h4(#find-by-custom-sql). Find by custom SQL
323 1
324 6 Kien La
If, for some reason, you need to create a complicated SQL query beyond the capacity of "finder options":/projects/main/wiki/Finders#finder-options, then you can pass a custom SQL query through Model::find_by_sql(). This will render your model as "readonly":/projects/main/wiki/Finders#read-only so that you cannot use any write methods on your returned model(s).
325 1
326 1
*Caution:* find_by_sql() will NOT prevent SQL injection like all other finder methods. The burden to secure your custom find_by_sql() query is on you.
327 1
328 1
<pre class="code"><code class="php">
329 1
# this will return a single result of a book model with only the title as an attirubte
330 1
$book = Book::find_by_sql('select title from `books`');
331 1
 
332 1
# you can even select from another table
333 1
$cached_book = Book::find_by_sql('select * from books_cache');
334 1
# this will give you the attributes from the books_cache table
335 1
</code></pre>