relationship.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php namespace Laravel\Database\Eloquent\Relationships;
  2. use Laravel\Database\Eloquent\Model;
  3. use Laravel\Database\Eloquent\Query;
  4. abstract class Relationship extends Query {
  5. /**
  6. * The base model for the relationship.
  7. *
  8. * @var Model
  9. */
  10. protected $base;
  11. /**
  12. * Create a new has one or many association instance.
  13. *
  14. * @param Model $model
  15. * @param string $associated
  16. * @param string $foreign
  17. * @return void
  18. */
  19. public function __construct($model, $associated, $foreign)
  20. {
  21. $this->foreign = $foreign;
  22. // We will go ahead and set the model and associated instances on the relationship
  23. // to match the relationship targets passed in from the model. These will allow
  24. // us to gather more inforamtion on the relationship.
  25. $this->model = ($associated instanceof Model) ? $associated : new $associated;
  26. if ($model instanceof Model)
  27. {
  28. $this->base = $model;
  29. }
  30. else
  31. {
  32. $this->base = new $model;
  33. }
  34. // Next we'll set the fluent query builder for the relationship and constrain
  35. // the query such that it only returns the models that are appropriate for
  36. // the relationship, typically by setting the foreign key.
  37. $this->table = $this->query();
  38. $this->constrain();
  39. }
  40. /**
  41. * Get the foreign key name for the given model.
  42. *
  43. * @param string $model
  44. * @param string $foreign
  45. * @return string
  46. */
  47. public static function foreign($model, $foreign = null)
  48. {
  49. if ( ! is_null($foreign)) return $foreign;
  50. // If the model is an object we'll simply get the class of the object and
  51. // then take the basename, which is simply the object name minus the
  52. // namespace, and we'll append "_id" to the name.
  53. if (is_object($model))
  54. {
  55. $model = class_basename($model);
  56. }
  57. return strtolower(basename($model).'_id');
  58. }
  59. /**
  60. * Get a freshly instantiated instance of the related model class.
  61. *
  62. * @param array $attributes
  63. * @return Model
  64. */
  65. protected function fresh_model($attributes = array())
  66. {
  67. $class = get_class($this->model);
  68. return new $class($attributes);
  69. }
  70. /**
  71. * Get the foreign key for the relationship.
  72. *
  73. * @return string
  74. */
  75. protected function foreign_key()
  76. {
  77. return static::foreign($this->base, $this->foreign);
  78. }
  79. }