model.php 17.5 KB
Newer Older
Taylor Otwell committed
1 2
<?php namespace Laravel\Database\Eloquent;

3
use Laravel\Str;
4
use Laravel\Event;
Taylor Otwell committed
5
use Laravel\Database;
Taylor Otwell committed
6
use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;
Taylor Otwell committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

abstract class Model {

	/**
	 * All of the model's attributes.
	 *
	 * @var array
	 */
	public $attributes = array();

	/**
	 * The model's attributes in their original state.
	 *
	 * @var array
	 */
	public $original = array();

	/**
	 * The relationships that have been loaded for the query.
	 *
	 * @var array
	 */
	public $relationships = array();

	/**
	 * Indicates if the model exists in the database.
	 *
	 * @var bool
	 */
	public $exists = false;

	/**
	 * The relationships that should be eagerly loaded.
	 *
	 * @var array
	 */
	public $includes = array();

	/**
	 * The primary key for the model on the database table.
	 *
	 * @var string
	 */
	public static $key = 'id';

	/**
	 * The attributes that are accessible for mass assignment.
	 *
	 * @var array
	 */
	public static $accessible;

	/**
60 61 62 63 64 65 66
	 * The attributes that should be excluded from to_array.
	 *
	 * @var array
	 */
	public static $hidden = array();

	/**
Taylor Otwell committed
67 68 69 70
	 * Indicates if the model has update and creation timestamps.
	 *
	 * @var bool
	 */
71
	public static $timestamps = true;
Taylor Otwell committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

	/**
	 * The name of the table associated with the model.
	 *
	 * @var string
	 */
	public static $table;

	/**
	 * The name of the database connection that should be used for the model.
	 *
	 * @var string
	 */
	public static $connection;

	/**
	 * The name of the sequence associated with the model.
	 *
	 * @var string
	 */
	public static $sequence;

	/**
95 96 97 98 99 100 101
	 * The default number of models to show per page when paginating.
	 *
	 * @var int
	 */
	public static $per_page = 20;

	/**
Taylor Otwell committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
	 * Create a new Eloquent model instance.
	 *
	 * @param  array  $attributes
	 * @param  bool   $exists
	 * @return void
	 */
	public function __construct($attributes = array(), $exists = false)
	{
		$this->exists = $exists;

		$this->fill($attributes);
	}

	/**
	 * Hydrate the model with an array of attributes.
	 *
	 * @param  array  $attributes
119
	 * @param  bool   $raw
Taylor Otwell committed
120 121
	 * @return Model
	 */
122
	public function fill(array $attributes, $raw = false)
Taylor Otwell committed
123 124 125
	{
		foreach ($attributes as $key => $value)
		{
126 127 128 129 130 131 132 133 134 135
			// If the "raw" flag is set, it means that we'll just load every value from
			// the array directly into the attributes, without any accessibility or
			// mutators being accounted for. What you pass in is what you get.
			if ($raw)
			{
				$this->set_attribute($key, $value);

				continue;
			}

Taylor Otwell committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
			// If the "accessible" property is an array, the developer is limiting the
			// attributes that may be mass assigned, and we need to verify that the
			// current attribute is included in that list of allowed attributes.
			if (is_array(static::$accessible))
			{
				if (in_array($key, static::$accessible))
				{
					$this->$key = $value;
				}
			}

			// If the "accessible" property is not an array, no attributes have been
			// white-listed and we are free to set the value of the attribute to
			// the value that has been passed into the method without a check.
			else
			{
				$this->$key = $value;
			}
		}

156 157 158
		// If the original attribute values have not been set, we will set
		// them to the values passed to this method allowing us to easily
		// check if the model has changed since hydration.
Taylor Otwell committed
159 160 161 162 163 164 165 166 167
		if (count($this->original) === 0)
		{
			$this->original = $this->attributes;
		}

		return $this;
	}

	/**
168 169 170 171 172 173 174 175 176 177 178 179 180
	 * Fill the model with the contents of the array.
	 *
	 * No mutators or accessibility checks will be accounted for.
	 *
	 * @param  array  $attributes
	 * @return Model
	 */
	public function fill_raw(array $attributes)
	{
		return $this->fill($attributes, true);
	}

	/**
181 182 183 184 185
	 * Set the accessible attributes for the given model.
	 *
	 * @param  array  $attributes
	 * @return void
	 */
186
	public static function accessible($attributes = null)
187
	{
188 189
		if (is_null($attributes)) return static::$accessible;

190 191 192 193
		static::$accessible = $attributes;
	}

	/**
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	 * Create a new model and store it in the database.
	 *
	 * If save is successful, the model will be returned, otherwise false.
	 *
	 * @param  array        $attributes
	 * @return Model|false
	 */
	public static function create($attributes)
	{
		$model = new static($attributes);

		$success = $model->save();

		return ($success) ? $model : false;
	}

	/**
211 212 213 214 215 216 217 218 219 220
	 * Update a model instance in the database.
	 *
	 * @param  mixed  $id
	 * @param  array  $attributes
	 * @return int
	 */
	public static function update($id, $attributes)
	{
		$model = new static(array(), true);

221
		if (static::$timestamps) $attributes['updated_at'] = new \DateTime;
222 223 224 225 226

		return $model->query()->where($model->key(), '=', $id)->update($attributes);
	}

	/**
Taylor Otwell committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	 * Find a model by its primary key.
	 *
	 * @param  string  $id
	 * @param  array   $columns
	 * @return Model
	 */
	public static function find($id, $columns = array('*'))
	{
		$model = new static;

		return $model->query()->where(static::$key, '=', $id)->first($columns);
	}

	/**
	 * Get all of the models in the database.
	 *
	 * @return array
	 */
	public static function all()
	{
247
		return with(new static)->query()->get();
Taylor Otwell committed
248 249 250 251 252 253 254 255 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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	}

	/**
	 * The relationships that should be eagerly loaded by the query.
	 *
	 * @param  array  $includes
	 * @return Model
	 */
	public function _with($includes)
	{
		$this->includes = (array) $includes;

		return $this;
	}

	/**
	 * Get the query for a one-to-one association.
	 *
	 * @param  string        $model
	 * @param  string        $foreign
	 * @return Relationship
	 */
	public function has_one($model, $foreign = null)
	{
		return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
	}

	/**
	 * Get the query for a one-to-many association.
	 *
	 * @param  string        $model
	 * @param  string        $foreign
	 * @return Relationship
	 */
	public function has_many($model, $foreign = null)
	{
		return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
	}

	/**
	 * Get the query for a one-to-one / many association.
	 *
	 * @param  string        $type
	 * @param  string        $model
	 * @param  string        $foreign
	 * @return Relationship
	 */
	protected function has_one_or_many($type, $model, $foreign)
	{
		if ($type == 'has_one')
		{
			return new Relationships\Has_One($this, $model, $foreign);
		}
		else
		{
			return new Relationships\Has_Many($this, $model, $foreign);
		}
	}

	/**
	 * Get the query for a one-to-one (inverse) relationship.
	 *
	 * @param  string        $model
	 * @param  string        $foreign
	 * @return Relationship
	 */
	public function belongs_to($model, $foreign = null)
	{
		// If no foreign key is specified for the relationship, we will assume that the
		// name of the calling function matches the foreign key. For example, if the
		// calling function is "manager", we'll assume the key is "manager_id".
		if (is_null($foreign))
		{
			list(, $caller) = debug_backtrace(false);

			$foreign = "{$caller['function']}_id";
		}

		return new Relationships\Belongs_To($this, $model, $foreign);
	}

	/**
	 * Get the query for a many-to-many relationship.
	 *
	 * @param  string        $model
	 * @param  string        $table
	 * @param  string        $foreign
	 * @param  string        $other
	 * @return Relationship
	 */
338
	public function has_many_and_belongs_to($model, $table = null, $foreign = null, $other = null)
Taylor Otwell committed
339 340 341 342 343
	{
		return new Has_Many_And_Belongs_To($this, $model, $table, $foreign, $other);
	}

	/**
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
	 * Save the model and all of its relations to the database.
	 *
	 * @return bool
	 */
	public function push()
	{
		$this->save();

		// To sync all of the relationships to the database, we will simply spin through
		// the relationships, calling the "push" method on each of the models in that
		// given relationship, this should ensure that each model is saved.
		foreach ($this->relationships as $name => $models)
		{
			if ( ! is_array($models))
			{
				$models = array($models);
			}

			foreach ($models as $model)
			{
				$model->push();
			}
		}
	}

	/**
Taylor Otwell committed
370 371 372 373 374 375 376 377 378 379 380 381 382
	 * Save the model instance to the database.
	 *
	 * @return bool
	 */
	public function save()
	{
		if ( ! $this->dirty()) return true;

		if (static::$timestamps)
		{
			$this->timestamp();
		}

383 384
		$this->fire_event('saving');

Taylor Otwell committed
385 386 387 388 389 390 391 392
		// If the model exists, we only need to update it in the database, and the update
		// will be considered successful if there is one affected row returned from the
		// fluent query instance. We'll set the where condition automatically.
		if ($this->exists)
		{
			$query = $this->query()->where(static::$key, '=', $this->get_key());

			$result = $query->update($this->get_dirty()) === 1;
393 394

			if ($result) $this->fire_event('updated');
Taylor Otwell committed
395 396 397 398 399 400 401 402 403 404 405 406
		}

		// If the model does not exist, we will insert the record and retrieve the last
		// insert ID that is associated with the model. If the ID returned is numeric
		// then we can consider the insert successful.
		else
		{
			$id = $this->query()->insert_get_id($this->attributes, $this->sequence());

			$this->set_key($id);

			$this->exists = $result = is_numeric($this->get_key());
407 408

			if ($result) $this->fire_event('created');
Taylor Otwell committed
409 410 411 412 413 414 415
		}

		// After the model has been "saved", we will set the original attributes to
		// match the current attributes so the model will not be viewed as being
		// dirty and subsequent calls won't hit the database.
		$this->original = $this->attributes;

416 417 418 419 420
		if ($result)
		{
			$this->fire_event('saved');
		}

Taylor Otwell committed
421 422 423 424
		return $result;
	}

	/**
425 426 427 428 429 430 431 432
	 * Delete the model from the database.
	 *
	 * @return int
	 */
	public function delete()
	{
		if ($this->exists)
		{
433 434 435 436 437 438 439
			$this->fire_event('deleting');

			$result = $this->query()->where(static::$key, '=', $this->get_key())->delete();

			$this->fire_event('deleted');

			return $result;
440 441 442 443
		}
	}

	/**
Taylor Otwell committed
444 445 446 447 448 449
	 * Set the update and creation timestamps on the model.
	 *
	 * @return void
	 */
	protected function timestamp()
	{
450
		$this->updated_at = new \DateTime;
Taylor Otwell committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

		if ( ! $this->exists) $this->created_at = $this->updated_at;
	}

	/**
	 * Get a new fluent query builder instance for the model.
	 *
	 * @return Query
	 */
	protected function query()
	{
		return new Query($this);
	}

	/**
466 467 468 469 470 471 472 473 474 475 476 477
	 * Sync the original attributes with the current attributes.
	 *
	 * @return bool
	 */
	final public function sync()
	{
		$this->original = $this->attributes;

		return true;
	}

	/**
Taylor Otwell committed
478 479 480 481 482 483 484
	 * Determine if a given attribute has changed from its original state.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	public function changed($attribute)
	{
485
		return array_get($this->attributes, $attribute) !== array_get($this->original, $attribute);
Taylor Otwell committed
486 487 488 489 490 491 492 493 494 495 496
	}

	/**
	 * Determine if the model has been changed from its original state.
	 *
	 * Models that haven't been persisted to storage are always considered dirty.
	 *
	 * @return bool
	 */
	public function dirty()
	{
497
		return ! $this->exists or count($this->get_dirty()) > 0;
Taylor Otwell committed
498 499 500
	}

	/**
501 502 503 504 505 506
	 * Get the name of the table associated with the model.
	 *
	 * @return string
	 */
	public function table()
	{
507
		return static::$table ?: strtolower(Str::plural(class_basename($this)));
508 509 510
	}

	/**
Taylor Otwell committed
511 512 513 514 515 516
	 * Get the dirty attributes for the model.
	 *
	 * @return array
	 */
	public function get_dirty()
	{
517 518 519 520 521 522 523 524 525 526 527
		$dirty = array();

		foreach ($this->attributes as $key => $value)
		{
			if ( ! isset($this->original[$key]) or $value !== $this->original[$key])
			{
				$dirty[$key] = $value;
			}
		}

		return $dirty;
Taylor Otwell committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
	}

	/**
	 * Get the value of the primary key for the model.
	 *
	 * @return int
	 */
	public function get_key()
	{
		return $this->get_attribute(static::$key);
	}

	/**
	 * Set the value of the primary key for the model.
	 *
	 * @param  int   $value
	 * @return void
	 */
	public function set_key($value)
	{
		return $this->set_attribute(static::$key, $value);
	}

	/**
	 * Get a given attribute from the model.
	 *
	 * @param  string  $key
	 */
	public function get_attribute($key)
	{
Taylor Otwell committed
558
		return array_get($this->attributes, $key);
Taylor Otwell committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
	}

	/**
	 * Set an attribute's value on the model.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public function set_attribute($key, $value)
	{
		$this->attributes[$key] = $value;
	}

	/**
574 575 576 577 578 579 580 581 582 583 584 585
	 * Remove an attribute from the model.
	 *
	 * @param  string  $key
	 */
	final public function purge($key)
	{
		unset($this->original[$key]);

		unset($this->attributes[$key]);
	}

	/**
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	 * Get the model attributes and relationships in array form.
	 *
	 * @return array
	 */
	public function to_array()
	{
		$attributes = array();

		// First we need to gather all of the regular attributes. If the attribute
		// exists in the array of "hidden" attributes, it will not be added to
		// the array so we can easily exclude things like passwords, etc.
		foreach (array_keys($this->attributes) as $attribute)
		{
			if ( ! in_array($attribute, static::$hidden))
			{
				$attributes[$attribute] = $this->$attribute;
			}
		}

		foreach ($this->relationships as $name => $models)
		{
			// If the relationship is not a "to-many" relationship, we can just
			// to_array the related model and add it as an attribute to the
			// array of existing regular attributes we gathered.
610
			if ($models instanceof Model)
611 612 613 614 615 616 617
			{
				$attributes[$name] = $models->to_array();
			}

			// If the relationship is a "to-many" relationship we need to spin
			// through each of the related models and add each one with the
			// to_array method, keying them both by name and ID.
618
			elseif (is_array($models))
619 620 621 622 623 624
			{
				foreach ($models as $id => $model)
				{
					$attributes[$name][$id] = $model->to_array();
				}
			}
625 626 627 628
			elseif (is_null($models))
			{
				$attributes[$name] = $models;
			}
629 630 631 632 633 634
		}

		return $attributes;
	}

	/**
635 636 637 638 639 640 641 642 643 644 645 646 647
	 * Fire a given event for the model.
	 *
	 * @param  string  $event
	 * @return array
	 */
	protected function fire_event($event)
	{
		$events = array("eloquent.{$event}", "eloquent.{$event}: ".get_class($this));

		Event::fire($events, array($this));
	}

	/**
Taylor Otwell committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
	 * Handle the dynamic retrieval of attributes and associations.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	public function __get($key)
	{
		// First we will check to see if the requested key is an already loaded
		// relationship and return it if it is. All relationships are stored
		// in the special relationships array so they are not persisted.
		if (array_key_exists($key, $this->relationships))
		{
			return $this->relationships[$key];
		}

663 664 665 666 667 668 669 670
		// Next we'll check if the requested key is in the array of attributes
		// for the model. These are simply regular properties that typically
		// correspond to a single column on the database for the model.
		elseif (array_key_exists($key, $this->attributes))
		{
			return $this->{"get_{$key}"}();
		}

Taylor Otwell committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		// If the item is not a loaded relationship, it may be a relationship
		// that hasn't been loaded yet. If it is, we will lazy load it and
		// set the value of the relationship in the relationship array.
		elseif (method_exists($this, $key))
		{
			return $this->relationships[$key] = $this->$key()->results();
		}

		// Finally we will just assume the requested key is just a regular
		// attribute and attempt to call the getter method for it, which
		// will fall into the __call method if one doesn't exist.
		else
		{
			return $this->{"get_{$key}"}();
		}
	}

	/**
	 * Handle the dynamic setting of attributes.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public function __set($key, $value)
	{
		$this->{"set_{$key}"}($value);
	}

	/**
701 702 703 704 705 706 707 708 709 710 711
	 * Determine if an attribute exists on the model.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public function __isset($key)
	{
		foreach (array('attributes', 'relationships') as $source)
		{
			if (array_key_exists($key, $this->$source)) return true;
		}
712 713
		
		if (method_exists($this, $key)) return true;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
	}

	/**
	 * Remove an attribute from the model.
	 *
	 * @param  string  $key
	 * @return void
	 */
	public function __unset($key)
	{
		foreach (array('attributes', 'relationships') as $source)
		{
			unset($this->$source[$key]);
		}
	}

	/**
Taylor Otwell committed
731 732 733 734 735 736 737 738
	 * Handle dynamic method calls on the model.
	 *
	 * @param  string  $method
	 * @param  array   $parameters
	 * @return mixed
	 */
	public function __call($method, $parameters)
	{
739
		$meta = array('key', 'table', 'connection', 'sequence', 'per_page', 'timestamps');
740

Taylor Otwell committed
741 742 743
		// If the method is actually the name of a static property on the model we'll
		// return the value of the static property. This makes it convenient for
		// relationships to access these values off of the instances.
744
		if (in_array($method, $meta))
Taylor Otwell committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
		{
			return static::$$method;
		}

		// Some methods need to be accessed both staticly and non-staticly so we'll
		// keep underscored methods of those methods and intercept calls to them
		// here so they can be called either way on the model instance.
		if (in_array($method, array('with')))
		{
			return call_user_func_array(array($this, '_'.$method), $parameters);
		}

		// First we want to see if the method is a getter / setter for an attribute.
		// If it is, we'll call the basic getter and setter method for the model
		// to perform the appropriate action based on the method.
		if (starts_with($method, 'get_'))
		{
762
			return $this->get_attribute(substr($method, 4));
Taylor Otwell committed
763 764 765
		}
		elseif (starts_with($method, 'set_'))
		{
766
			$this->set_attribute(substr($method, 4), $parameters[0]);
Taylor Otwell committed
767
		}
768

Taylor Otwell committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
		// Finally we will assume that the method is actually the beginning of a
		// query, such as "where", and will create a new query instance and
		// call the method on the query instance, returning it after.
		else
		{
			return call_user_func_array(array($this->query(), $method), $parameters);
		}
	}

	/**
	 * Dynamically handle static method calls on the model.
	 *
	 * @param  string  $method
	 * @param  array   $parameters
	 * @return mixed
	 */
	public static function __callStatic($method, $parameters)
	{
		$model = get_called_class();

		return call_user_func_array(array(new $model, $method), $parameters);
	}

}