relationship.php 2.35 KB
Newer Older
Taylor Otwell committed
1 2 3 4
<?php namespace Laravel\Database\Eloquent\Relationships;

use Laravel\Database\Eloquent\Model;
use Laravel\Database\Eloquent\Query;
Taylor Otwell committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

abstract class Relationship extends Query {

	/**
	 * The base model for the relationship.
	 *
	 * @var Model
	 */
	protected $base;

	/**
	 * Create a new has one or many association instance.
	 *
	 * @param  Model   $model
	 * @param  string  $associated
	 * @param  string  $foreign
	 * @return void
	 */
	public function __construct($model, $associated, $foreign)
	{
		$this->foreign = $foreign;

27 28 29 30 31 32 33 34 35 36 37
		// We will go ahead and set the model and associated instances on the
		// relationship to match the relationship targets passed in from the
		// model. These will allow us to gather the relationship info.
		if ($associated instanceof Model)
		{
			$this->model = $associated;
		}
		else
		{
			$this->model = new $associated;
		}
Taylor Otwell committed
38

39 40 41
		// For relationships, we'll set the base model to be the model being
		// associated from. This model contains the value of the foreign
		// key needed to connect to the associated model.
Taylor Otwell committed
42 43 44 45 46 47 48 49 50
		if ($model instanceof Model)
		{
			$this->base = $model;
		}
		else
		{
			$this->base = new $model;
		}

51 52 53
		// Next we'll set the fluent query builder for the relationship and
		// constrain the query such that it only returns the models that
		// are appropriate for the relationship.
54
		$this->table = $this->table();
Taylor Otwell committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

		$this->constrain();
	}

	/**
	 * Get the foreign key name for the given model.
	 *
	 * @param  string  $model
	 * @param  string  $foreign
	 * @return string
	 */
	public static function foreign($model, $foreign = null)
	{
		if ( ! is_null($foreign)) return $foreign;

70
		// If the model is an object we'll simply get the class of the object and
Taylor Otwell committed
71 72 73 74
		// then take the basename, which is simply the object name minus the
		// namespace, and we'll append "_id" to the name.
		if (is_object($model))
		{
75
			$model = class_basename($model);
Taylor Otwell committed
76 77 78 79 80 81
		}

		return strtolower(basename($model).'_id');
	}

	/**
82 83 84 85 86 87 88 89 90 91 92 93 94
	 * Get a freshly instantiated instance of the related model class.
	 *
	 * @param  array  $attributes
	 * @return Model
	 */
	protected function fresh_model($attributes = array())
	{
		$class = get_class($this->model);

		return new $class($attributes);
	}

	/**
Taylor Otwell committed
95 96 97 98
	 * Get the foreign key for the relationship.
	 *
	 * @return string
	 */
99
	public function foreign_key()
Taylor Otwell committed
100
	{
101
		return static::foreign($this->base, $this->foreign);
Taylor Otwell committed
102 103 104
	}

}