query.php 14.2 KB
Newer Older
1
<?php namespace Laravel\Database; use Laravel\Paginator;
2 3 4 5

class Query {

	/**
Taylor Otwell committed
6
	 * The database connection.
7
	 *
8
	 * @var Connection
9
	 */
Taylor Otwell committed
10
	public $connection;
11 12

	/**
13
	 * The query grammar instance.
14
	 *
15
	 * @var Grammars\Grammar
16
	 */
17
	public $grammar;
18 19

	/**
20 21
	 * The SELECT clause.
	 *
Taylor Otwell committed
22
	 * @var array
23
	 */
Taylor Otwell committed
24
	public $selects;
25 26

	/**
27 28
	 * If the query is performing an aggregate function, this will contain
	 * the column and and function to use when aggregating.
29
	 *
Taylor Otwell committed
30
	 * @var array
31
	 */
Taylor Otwell committed
32
	public $aggregate;
33 34

	/**
Taylor Otwell committed
35
	 * Indicates if the query should return distinct results.
36
	 *
Taylor Otwell committed
37
	 * @var bool
38
	 */
Taylor Otwell committed
39
	public $distinct = false;
40 41 42 43 44 45

	/**
	 * The table name.
	 *
	 * @var string
	 */
Taylor Otwell committed
46
	public $from;
47 48

	/**
Taylor Otwell committed
49
	 * The table joins.
50
	 *
Taylor Otwell committed
51
	 * @var array
52
	 */
Taylor Otwell committed
53
	public $joins;
54 55

	/**
Taylor Otwell committed
56
	 * The WHERE clauses.
57
	 *
Taylor Otwell committed
58
	 * @var array
59
	 */
Taylor Otwell committed
60
	public $wheres;
61 62

	/**
Taylor Otwell committed
63
	 * The ORDER BY clauses.
64 65 66
	 *
	 * @var array
	 */
Taylor Otwell committed
67
	public $orderings;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

	/**
	 * The LIMIT value.
	 *
	 * @var int
	 */
	public $limit;

	/**
	 * The OFFSET value.
	 *
	 * @var int
	 */
	public $offset;

	/**
	 * The query value bindings.
	 *
	 * @var array
	 */
	public $bindings = array();

	/**
	 * Create a new query instance.
	 *
Taylor Otwell committed
93 94 95
	 * @param  Connection        $connection
	 * @param  Grammars\Grammar  $grammar
	 * @param  string            $table
96 97
	 * @return void
	 */
98
	public function __construct(Connection $connection, Grammars\Grammar $grammar, $table)
99
	{
Taylor Otwell committed
100
		$this->from = $table;
101
		$this->grammar = $grammar;
102
		$this->connection = $connection;
103 104 105 106 107 108 109 110 111 112
	}

	/**
	 * Force the query to return distinct results.
	 *
	 * @return Query
	 */
	public function distinct()
	{
		$this->distinct = true;
Taylor Otwell committed
113

114 115 116 117
		return $this;
	}

	/**
Taylor Otwell committed
118 119
	 * Add an array of columns to the SELECT clause.
	 *
120
	 * @param  array  $columns
121 122
	 * @return Query
	 */
123
	public function select($columns = array('*'))
124
	{
Taylor Otwell committed
125
		$this->selects = (array) $columns;
126 127 128 129 130

		return $this;
	}

	/**
Taylor Otwell committed
131
	 * Add a join clause to the query.
132
	 *
133 134 135 136 137 138 139 140 141
	 * @param  string  $table
	 * @param  string  $column1
	 * @param  string  $operator
	 * @param  string  $column2
	 * @param  string  $type
	 * @return Query
	 */
	public function join($table, $column1, $operator, $column2, $type = 'INNER')
	{
Taylor Otwell committed
142
		$this->joins[] = compact('type', 'table', 'column1', 'operator', 'column2');
Taylor Otwell committed
143

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		return $this;
	}

	/**
	 * Add a left join to the query.
	 *
	 * @param  string  $table
	 * @param  string  $column1
	 * @param  string  $operator
	 * @param  string  $column2
	 * @return Query
	 */
	public function left_join($table, $column1, $operator, $column2)
	{
		return $this->join($table, $column1, $operator, $column2, 'LEFT');
	}

	/**
Taylor Otwell committed
162
	 * Reset the where clause to its initial state. All bindings will be cleared.
Taylor Otwell committed
163 164 165 166 167
	 *
	 * @return void
	 */
	public function reset_where()
	{
168
		list($this->wheres, $this->bindings) = array(array(), array());
Taylor Otwell committed
169 170 171
	}

	/**
172 173 174 175 176 177 178 179 180
	 * Add a raw where condition to the query.
	 *
	 * @param  string  $where
	 * @param  array   $bindings
	 * @param  string  $connector
	 * @return Query
	 */
	public function raw_where($where, $bindings = array(), $connector = 'AND')
	{
Taylor Otwell committed
181
		$this->wheres[] = array('type' => 'raw', 'connector' => $connector, 'sql' => $where);
Taylor Otwell committed
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		$this->bindings = array_merge($this->bindings, $bindings);

		return $this;
	}

	/**
	 * Add a raw or where condition to the query.
	 *
	 * @param  string  $where
	 * @param  array   $bindings
	 * @return Query
	 */
	public function raw_or_where($where, $bindings = array())
	{
		return $this->raw_where($where, $bindings, 'OR');
	}

	/**
	 * Add a where condition to the query.
	 *
	 * @param  string  $column
	 * @param  string  $operator
	 * @param  mixed   $value
	 * @param  string  $connector
	 * @return Query
	 */
	public function where($column, $operator, $value, $connector = 'AND')
	{
Taylor Otwell committed
211 212
		$this->wheres[] = array_merge(array('type' => 'where'), compact('column', 'operator', 'value', 'connector'));

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		$this->bindings[] = $value;

		return $this;
	}

	/**
	 * Add an or where condition to the query.
	 *
	 * @param  string  $column
	 * @param  string  $operator
	 * @param  mixed   $value
	 * @return Query
	 */
	public function or_where($column, $operator, $value)
	{
		return $this->where($column, $operator, $value, 'OR');
	}

	/**
232
	 * Add an or where condition for the primary key to the query.
Taylor Otwell committed
233
	 *
234 235 236 237 238 239 240 241 242
	 * @param  mixed  $value
	 * @return Query
	 */
	public function or_where_id($value)
	{
		return $this->or_where('id', '=', $value);		
	}

	/**
243 244 245 246 247
	 * Add a where in condition to the query.
	 *
	 * @param  string  $column
	 * @param  array   $values
	 * @param  string  $connector
Taylor Otwell committed
248
	 * @param  bool    $not
249 250
	 * @return Query
	 */
Taylor Otwell committed
251
	public function where_in($column, $values, $connector = 'AND', $not = false)
252
	{
253 254 255
		$type = ($not) ? 'where_not_in' : 'where_in';

		$this->wheres[] = compact('type', 'column', 'values', 'connector');
Taylor Otwell committed
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
		$this->bindings = array_merge($this->bindings, $values);

		return $this;
	}

	/**
	 * Add an or where in condition to the query.
	 *
	 * @param  string  $column
	 * @param  array   $values
	 * @return Query
	 */
	public function or_where_in($column, $values)
	{
		return $this->where_in($column, $values, 'OR');
	}

	/**
	 * Add a where not in condition to the query.
	 *
	 * @param  string  $column
	 * @param  array   $values
	 * @param  string  $connector
	 * @return Query
	 */
	public function where_not_in($column, $values, $connector = 'AND')
	{
Taylor Otwell committed
284
		return $this->where_in($column, $values, $connector, true);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	}

	/**
	 * Add an or where not in condition to the query.
	 *
	 * @param  string  $column
	 * @param  array   $values
	 * @return Query
	 */
	public function or_where_not_in($column, $values)
	{
		return $this->where_not_in($column, $values, 'OR');
	}

	/**
	 * Add a where null condition to the query.
	 *
	 * @param  string  $column
	 * @param  string  $connector
Taylor Otwell committed
304
	 * @param  bool    $not
305 306
	 * @return Query
	 */
Taylor Otwell committed
307
	public function where_null($column, $connector = 'AND', $not = false)
308
	{
309 310 311
		$type = ($not) ? 'where_not_null' : 'where_null';

		$this->wheres[] = compact('type', 'column', 'connector');
Taylor Otwell committed
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
		return $this;
	}

	/**
	 * Add an or where null condition to the query.
	 *
	 * @param  string  $column
	 * @return Query
	 */
	public function or_where_null($column)
	{
		return $this->where_null($column, 'OR');
	}

	/**
	 * Add a where not null condition to the query.
	 *
	 * @param  string  $column
	 * @param  string  $connector
	 * @return Query
	 */
	public function where_not_null($column, $connector = 'AND')
	{
Taylor Otwell committed
336
		return $this->where_null($column, $connector, true);
337 338 339 340 341 342 343 344 345 346 347 348 349 350
	}

	/**
	 * Add an or where not null condition to the query.
	 *
	 * @param  string  $column
	 * @return Query
	 */
	public function or_where_not_null($column)
	{
		return $this->where_not_null($column, 'OR');
	}

	/**
Taylor Otwell committed
351 352
	 * Add dynamic where conditions to the query.
	 *
Taylor Otwell committed
353 354 355
	 * Dynamic queries are caught by the __call magic method and are parsed here.
	 * They provide a convenient, expressive API for building simple conditions.
	 *
Taylor Otwell committed
356 357 358 359 360 361 362 363 364 365 366 367
	 * @param  string  $method
	 * @param  array   $parameters
	 * @return Query
	 */
	private function dynamic_where($method, $parameters)
	{
		// Strip the "where_" off of the method.
		$finder = substr($method, 6);

		// Split the column names from the connectors.
		$segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);

368 369 370
		// The connector variable will determine which connector will be
		// used for the condition. We'll change it as we come across new
		// connectors in the dynamic method string.
Taylor Otwell committed
371
		//
372 373 374
		// The index variable helps us get the correct parameter value
		// for the where condition. We increment it each time we add
		// a condition to the query.
Taylor Otwell committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		$connector = 'AND';

		$index = 0;

		foreach ($segments as $segment)
		{
			if ($segment != '_and_' and $segment != '_or_')
			{
				$this->where($segment, '=', $parameters[$index], $connector);

				$index++;
			}
			else
			{
				$connector = trim(strtoupper($segment), '_');
			}
		}

		return $this;
	}

	/**
397 398 399 400 401 402
	 * Add an ordering to the query.
	 *
	 * @param  string  $column
	 * @param  string  $direction
	 * @return Query
	 */
403
	public function order_by($column, $direction = 'asc')
404
	{
Taylor Otwell committed
405
		$this->orderings[] = compact('column', 'direction');
406

407 408 409 410 411 412 413 414 415 416 417
		return $this;
	}

	/**
	 * Set the query offset.
	 *
	 * @param  int  $value
	 * @return Query
	 */
	public function skip($value)
	{
Taylor Otwell committed
418 419
		$this->offset = $value;

420 421 422 423 424 425 426 427 428 429 430
		return $this;
	}

	/**
	 * Set the query limit.
	 *
	 * @param  int  $value
	 * @return Query
	 */
	public function take($value)
	{
Taylor Otwell committed
431 432
		$this->limit = $value;

433 434 435 436
		return $this;
	}

	/**
437 438 439 440 441 442
	 * Set the query limit and offset for a given page and item per page count.
	 *
	 * @param  int    $page
	 * @param  int    $per_page
	 * @return Query
	 */
Taylor Otwell committed
443
	public function for_page($page, $per_page)
444
	{
Taylor Otwell committed
445
		return $this->skip(($page - 1) * $per_page)->take($per_page);
446 447 448
	}

	/**
Taylor Otwell committed
449
	 * Find a record by the primary key.
450
	 *
Taylor Otwell committed
451
	 * @param  int     $id
452
	 * @param  array   $columns
453 454
	 * @return object
	 */
Taylor Otwell committed
455
	public function find($id, $columns = array('*'))
456
	{
Taylor Otwell committed
457
		return $this->where('id', '=', $id)->first($columns);
458 459 460
	}

	/**
461
	 * Execute the query as a SELECT statement and return a single column.
462 463 464 465
	 *
	 * @param  string  $column
	 * @return mixed
	 */
466
	public function only($column)
467
	{
468
		$this->select(array($column));
Taylor Otwell committed
469

470
		return $this->connection->only($this->grammar->select($this), $this->bindings);
471 472 473
	}

	/**
Taylor Otwell committed
474
	 * Execute the query as a SELECT statement and return the first result.
475
	 *
476 477 478 479
	 * If a single column is selected from the database, only the value of that column will be returned.
	 *
	 * @param  array  $columns
	 * @return mixed
480
	 */
Taylor Otwell committed
481
	public function first($columns = array('*'))
482
	{
483 484
		$columns = (array) $columns;

485
		return (count($results = $this->take(1)->get($columns)) > 0) ? $results[0] : null;
Taylor Otwell committed
486 487 488 489 490 491 492 493 494 495
	}

	/**
	 * Execute the query as a SELECT statement.
	 *
	 * @param  array  $columns
	 * @return array
	 */
	public function get($columns = array('*'))
	{
Taylor Otwell committed
496
		if (is_null($this->selects)) $this->select($columns);
Taylor Otwell committed
497

498
		$results = $this->connection->query($this->grammar->select($this), $this->bindings);
499

500 501 502
		// Reset the SELECT clause so more queries can be performed using
		// the same instance. This is helpful for getting aggregates and
		// then getting actual results.
Taylor Otwell committed
503
		$this->selects = null;
504 505 506 507 508

		return $results;
	}

	/**
509 510 511 512 513 514 515 516 517 518 519 520
	 * Get an aggregate value.
	 *
	 * @param  string  $aggregate
	 * @param  string  $column
	 * @return mixed
	 */
	private function aggregate($aggregator, $column)
	{
		$this->aggregate = compact('aggregator', 'column');

		$result = $this->connection->only($this->grammar->select($this), $this->bindings);

521 522 523
		// Reset the aggregate so more queries can be performed using
		// the same instance. This is helpful for getting aggregates
		// and then getting actual results.
524 525 526 527 528 529
		$this->aggregate = null;

		return $result;
	}

	/**
530 531 532 533 534 535
	 * Get the paginated query results as a Paginator instance.
	 *
	 * @param  int        $per_page
	 * @param  array      $columns
	 * @return Paginator
	 */
536
	public function paginate($per_page = 20, $columns = array('*'))
537
	{
538 539 540
		// Calculate the current page for the request. The page number
		// will be validated and adjusted by the Paginator class,
		// so we can assume it is valid.
541 542 543 544 545 546
		$page = Paginator::page($total = $this->count(), $per_page);

		return Paginator::make($this->for_page($page, $per_page)->get($columns), $total, $per_page);
	}

	/**
Taylor Otwell committed
547 548
	 * Insert an array of values into the database table.
	 *
549 550 551 552 553
	 * @param  array  $values
	 * @return bool
	 */
	public function insert($values)
	{
554 555 556
		// Force every insert to be treated like a batch insert to make creating
		// the binding array simpler since we can just spin through the inserted
		// rows as if there/ was more than one every time.
557 558 559 560 561 562 563 564 565 566
		if ( ! is_array(reset($values))) $values = array($values);

		$bindings = array();

		foreach ($values as $value)
		{
			$bindings = array_merge($bindings, array_values($value));
		}

		return $this->connection->query($this->grammar->insert($this, $values), $bindings);
567 568 569
	}

	/**
570 571
	 * Insert an array of values into the database table and
	 * return the value of the ID column.
Taylor Otwell committed
572
	 *
573 574
	 * @param  array   $values
	 * @param  string  $sequence
575 576
	 * @return int
	 */
577
	public function insert_get_id($values, $sequence = null)
578
	{
579
		$this->connection->query($this->grammar->insert($this, $values), array_values($values));
580

581
		return (int) $this->connection->pdo->lastInsertId($sequence);
Taylor Otwell committed
582 583 584
	}

	/**
585 586 587 588 589 590 591 592
	 * Increment the value of a column by a given amount.
	 *
	 * @param  string  $column
	 * @param  int     $amount
	 * @return int
	 */
	public function increment($column, $amount = 1)
	{
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
		return $this->adjust($column, $amount, ' + ');
	}

	/**
	 * Decrement the value of a column by a given amount.
	 *
	 * @param  string  $column
	 * @param  int     $amount
	 * @return int
	 */
	public function decrement($column, $amount = 1)
	{
		return $this->adjust($column, $amount, ' - ');
	}

	/**
	 * Adjust the value of a column up or down by a given amount.
	 *
	 * @param  string  $column
	 * @param  int     $amount
	 * @param  string  $operator
	 * @return int
	 */
	protected function adjust($column, $amount, $operator)
	{
		return $this->update(array($column => Manager::raw($this->grammar->wrap($column).$operator.$amount)));
619 620 621
	}

	/**
Taylor Otwell committed
622 623
	 * Update an array of values in the database table.
	 *
624
	 * @param  array  $values
Taylor Otwell committed
625
	 * @return int
626 627 628
	 */
	public function update($values)
	{
629 630 631
		$bindings =  array_merge(array_values($values), $this->bindings);

		return $this->connection->query($this->grammar->update($this, $values), $bindings);
632 633 634 635 636
	}

	/**
	 * Execute the query as a DELETE statement.
	 *
Taylor Otwell committed
637 638
	 * Optionally, an ID may be passed to the method do delete a specific row.
	 *
639
	 * @param  int   $id
Taylor Otwell committed
640
	 * @return int
641 642 643
	 */
	public function delete($id = null)
	{
644
		if ( ! is_null($id)) $this->where('id', '=', $id);
645

646
		return $this->connection->query($this->grammar->delete($this), $this->bindings);		
647 648 649
	}

	/**
Taylor Otwell committed
650
	 * Magic Method for handling dynamic functions.
Taylor Otwell committed
651
	 *
652 653
	 * This method handles all calls to aggregate functions as well
	 * as the construction of dynamic where clauses.
654 655 656
	 */
	public function __call($method, $parameters)
	{
657 658
		if (strpos($method, 'where_') === 0)
		{
Taylor Otwell committed
659
			return $this->dynamic_where($method, $parameters, $this);
660 661
		}

Taylor Otwell committed
662
		if (in_array($method, array('abs', 'count', 'min', 'max', 'avg', 'sum')))
663
		{
664 665 666 667 668 669 670 671
			if ($method == 'count')
			{
				return $this->aggregate(strtoupper($method), '*');
			}
			else
			{
				return $this->aggregate(strtoupper($method), $parameters[0]);
			}
672
		}
673 674

		throw new \Exception("Method [$method] is not defined on the Query class.");
675 676 677
	}

}