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

3
use Laravel\Str;
Taylor Otwell committed
4
use Laravel\Database;
Taylor Otwell committed
5
use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;
Taylor Otwell committed
6 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

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;

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

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

	/**
	 * 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;

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

	/**
Taylor Otwell committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
	 * 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
	 * @return Model
	 */
	public function fill($attributes)
	{
		$attributes = (array) $attributes;

		foreach ($attributes as $key => $value)
		{
			// 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;
			}
		}

146 147 148
		// 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
149 150 151 152 153 154 155 156 157
		if (count($this->original) === 0)
		{
			$this->original = $this->attributes;
		}

		return $this;
	}

	/**
158 159 160 161 162 163 164 165 166 167 168
	 * Set the accessible attributes for the given model.
	 *
	 * @param  array  $attributes
	 * @return void
	 */
	public static function accessible($attributes)
	{
		static::$accessible = $attributes;
	}

	/**
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	 * 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;
	}

	/**
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	 * 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);

		if (static::$timestamps) $attributes['updated_at'] = $model->get_timestamp();

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

	/**
Taylor Otwell committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	 * 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()
	{
222
		return with(new static)->query()->get();
Taylor Otwell committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 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
	}

	/**
	 * 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
	 */
313
	public function has_many_and_belongs_to($model, $table = null, $foreign = null, $other = null)
Taylor Otwell committed
314 315 316 317 318
	{
		return new Has_Many_And_Belongs_To($this, $model, $table, $foreign, $other);
	}

	/**
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
	 * 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
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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	 * Save the model instance to the database.
	 *
	 * @return bool
	 */
	public function save()
	{
		if ( ! $this->dirty()) return true;

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

		// 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;
		}

		// 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());
		}

		// 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;

		return $result;
	}

	/**
389 390 391 392 393 394 395 396 397 398 399 400 401
	 * Delete the model from the database.
	 *
	 * @return int
	 */
	public function delete()
	{
		if ($this->exists)
		{
			return $this->query()->where(static::$key, '=', $this->get_key())->delete();
		}
	}

	/**
Taylor Otwell committed
402 403 404 405 406 407
	 * Set the update and creation timestamps on the model.
	 *
	 * @return void
	 */
	protected function timestamp()
	{
408
		$this->updated_at = $this->get_timestamp();
Taylor Otwell committed
409 410 411 412 413 414 415 416 417

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

	/**
	 * Get the current timestamp in its storable form.
	 *
	 * @return mixed
	 */
418
	public function get_timestamp()
Taylor Otwell committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
	{
		return date('Y-m-d H:i:s');
	}

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

	/**
434 435 436 437 438 439 440 441 442 443 444 445
	 * Sync the original attributes with the current attributes.
	 *
	 * @return bool
	 */
	final public function sync()
	{
		$this->original = $this->attributes;

		return true;
	}

	/**
Taylor Otwell committed
446 447 448 449 450 451 452
	 * Determine if a given attribute has changed from its original state.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	public function changed($attribute)
	{
453
		return array_get($this->attributes, $attribute) !== array_get($this->original, $attribute);
Taylor Otwell committed
454 455 456 457 458 459 460 461 462 463 464
	}

	/**
	 * 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()
	{
465
		return ! $this->exists or count($this->get_dirty()) > 0;
Taylor Otwell committed
466 467 468
	}

	/**
469 470 471 472 473 474 475 476 477 478
	 * Get the name of the table associated with the model.
	 *
	 * @return string
	 */
	public function table()
	{
		return static::$table ?: strtolower(Str::plural(basename(get_class($this))));
	}

	/**
Taylor Otwell committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
	 * Get the dirty attributes for the model.
	 *
	 * @return array
	 */
	public function get_dirty()
	{
		return array_diff_assoc($this->attributes, $this->original);
	}

	/**
	 * 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
516
		return array_get($this->attributes, $key);
Taylor Otwell committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	}

	/**
	 * 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;
	}

	/**
532 533 534 535 536 537 538 539 540 541 542 543
	 * Remove an attribute from the model.
	 *
	 * @param  string  $key
	 */
	final public function purge($key)
	{
		unset($this->original[$key]);

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

	/**
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	 * 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.
			if ( ! is_array($models))
			{
				$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.
			else
			{
				foreach ($models as $id => $model)
				{
					$attributes[$name][$id] = $model->to_array();
				}
			}
		}

		return $attributes;
	}

	/**
Taylor Otwell committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
	 * 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];
		}

604 605 606 607 608 609 610 611
		// 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
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
		// 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);
	}

	/**
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
	 * 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;
		}
	}

	/**
	 * 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
670 671 672 673 674 675 676 677
	 * Handle dynamic method calls on the model.
	 *
	 * @param  string  $method
	 * @param  array   $parameters
	 * @return mixed
	 */
	public function __call($method, $parameters)
	{
678 679
		$meta = array('key', 'table', 'connection', 'sequence', 'per_page');

Taylor Otwell committed
680 681 682
		// 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.
683
		if (in_array($method, $meta))
Taylor Otwell committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		{
			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_'))
		{
701
			return $this->attributes[substr($method, 4)];
Taylor Otwell committed
702 703 704
		}
		elseif (starts_with($method, 'set_'))
		{
705
			$this->attributes[substr($method, 4)] = $parameters[0];
Taylor Otwell committed
706
		}
707

Taylor Otwell committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
		// 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);
	}

}