relate.php 2.53 KB
Newer Older
1 2 3 4 5 6 7 8
<?php namespace System\DB\Eloquent;

class Relate {

	/**
	 * Retrieve the query for a 1:1 relationship.
	 *
	 * @param  string  $model
9
	 * @param  string  $foreign_key
10 11 12
	 * @param  object  $eloquent
	 * @return mixed
	 */
13
	public static function has_one($model, $foreign_key, $eloquent)
14 15
	{
		$eloquent->relating = __FUNCTION__;
16
		return static::has_one_or_many($model, $foreign_key, $eloquent);
17 18 19 20 21 22
	}

	/**
	 * Retrieve the query for a 1:* relationship.
	 *
	 * @param  string  $model
23
	 * @param  string  $foreign_key
24 25 26
	 * @param  object  $eloquent
	 * @return mixed
	 */
27
	public static function has_many($model, $foreign_key, $eloquent)
28 29
	{
		$eloquent->relating = __FUNCTION__;
30
		return static::has_one_or_many($model, $foreign_key, $eloquent);
31 32 33 34 35 36
	}

	/**
	 * Retrieve the query for a 1:1 or 1:* relationship.
	 *
	 * @param  string  $model
37
	 * @param  string  $foreign_key
38 39 40
	 * @param  object  $eloquent
	 * @return mixed
	 */
41
	private static function has_one_or_many($model, $foreign_key, $eloquent)
42
	{
43
		$eloquent->relating_key = (is_null($foreign_key)) ? \System\Str::lower(get_class($eloquent)).'_id' : $foreign_key;
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
		return Factory::make($model)->where($eloquent->relating_key, '=', $eloquent->id);
	}

	/**
	 * Retrieve the query for a 1:1 belonging relationship.
	 *
	 * @param  array   $caller
	 * @param  string  $model
	 * @param  object  $eloquent
	 * @return mixed
	 */
	public static function belongs_to($caller, $model, $eloquent)
	{
		$eloquent->relating = __FUNCTION__;
		$eloquent->relating_key = $caller['function'].'_id';

		return Factory::make($model)->where('id', '=', $eloquent->attributes[$eloquent->relating_key]);
	}

	/**
	 * Retrieve the query for a *:* relationship.
	 *
	 * @param  string  $model
	 * @param  object  $eloquent
	 * @return mixed
	 */
	public static function has_many_and_belongs_to($model, $eloquent)
	{
		// -----------------------------------------------------
		// Get the models involved in the relationship.
		// -----------------------------------------------------
		$models = array(\System\Str::lower($model), \System\Str::lower(get_class($eloquent)));
		sort($models);

		$eloquent->relating_table = implode('_', $models);
		$eloquent->relating = __FUNCTION__;
		$eloquent->relating_key = $eloquent->relating_table.'.'.\System\Str::lower(get_class($eloquent)).'_id';

		return Factory::make($model)
							->select(Meta::table($model).'.*')
							->join($eloquent->relating_table, Meta::table($model).'.id', '=', $eloquent->relating_table.'.'.\System\Str::lower($model).'_id')
							->where($eloquent->relating_key, '=', $eloquent->id);
	}

}