Browse Source

batch read added to be consistent

Maurits van der Schee 8 years ago
parent
commit
41f3b24d84
3 changed files with 37 additions and 1 deletions
  1. 14
    0
      README.md
  2. 16
    1
      api.php
  3. 7
    0
      tests/tests.php

+ 14
- 0
README.md View File

@@ -313,6 +313,20 @@ Output:
313 313
 {"id":"1","name":"Internet"}
314 314
 ```
315 315
 
316
+### Read (multiple)
317
+
318
+If you want to read multiple objects you can use:
319
+
320
+```
321
+GET http://localhost/api.php/categories/1,2
322
+```
323
+
324
+Output:
325
+
326
+```
327
+[{"id":"1","name":"Internet"},{"id":"2","name":"Programming"}]
328
+```
329
+
316 330
 ### Update
317 331
 
318 332
 Editing a record is done with the PUT method. The call returns the rows affected.

+ 16
- 1
api.php View File

@@ -1238,6 +1238,20 @@ class PHP_CRUD_API {
1238 1238
 		return $object;
1239 1239
 	}
1240 1240
 
1241
+	protected function retrieveObjects($key,$fields,$filters,$tables) {
1242
+		$keyField = $key[1];
1243
+		$keys = explode(',',$key[0]);
1244
+		$rows = array();
1245
+		foreach ($keys as $key) {
1246
+			$result = $this->retrieveObject(array($key,$keyField),$fields,$filters,$tables);
1247
+			if ($result===null) {
1248
+				return null;
1249
+			}
1250
+			$rows[] = $result;
1251
+		}
1252
+		return $rows;
1253
+	}
1254
+
1241 1255
 	protected function createObject($input,$tables) {
1242 1256
 		if (!$input) return false;
1243 1257
 		$input = (array)$input;
@@ -1673,7 +1687,8 @@ class PHP_CRUD_API {
1673 1687
 
1674 1688
 	protected function readCommand($parameters) {
1675 1689
 		extract($parameters);
1676
-		$object = $this->retrieveObject($key,$fields,$filters,$tables);
1690
+		if ($multi) $object = $this->retrieveObjects($key,$fields,$filters,$tables);
1691
+		else $object = $this->retrieveObject($key,$fields,$filters,$tables);
1677 1692
 		if (!$object) $this->exitWith404('object');
1678 1693
 		$this->startOutput();
1679 1694
 		echo json_encode($object);

+ 7
- 0
tests/tests.php View File

@@ -216,6 +216,13 @@ class PHP_CRUD_API_Test extends PHPUnit_Framework_TestCase
216 216
 		$test->expect('{"id":"2","user_id":"1","category_id":"2","content":"It works!"}');
217 217
 	}
218 218
 
219
+	public function testReadPosts()
220
+	{
221
+		$test = new API($this);
222
+		$test->get('/posts/1,2');
223
+		$test->expect('[{"id":"1","user_id":"1","category_id":"1","content":"blog started"},{"id":"2","user_id":"1","category_id":"2","content":"It works!"}]');
224
+	}
225
+
219 226
 	public function testReadPostColumns()
220 227
 	{
221 228
 		$test = new API($this);

Loading…
Cancel
Save