relationship.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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
  23. // relationship to match the relationship targets passed in from the
  24. // model. These will allow us to gather the relationship info.
  25. if ($associated instanceof Model)
  26. {
  27. $this->model = $associated;
  28. }
  29. else
  30. {
  31. $this->model = new $associated;
  32. }
  33. // For relationships, we'll set the base model to be the model being
  34. // associated from. This model contains the value of the foreign
  35. // key needed to connect to the associated model.
  36. if ($model instanceof Model)
  37. {
  38. $this->base = $model;
  39. }
  40. else
  41. {
  42. $this->base = new $model;
  43. }
  44. // Next we'll set the fluent query builder for the relationship and
  45. // constrain the query such that it only returns the models that
  46. // are appropriate for the relationship.
  47. $this->table = $this->table();
  48. $this->constrain();
  49. }
  50. /**
  51. * Get the foreign key name for the given model.
  52. *
  53. * @param string $model
  54. * @param string $foreign
  55. * @return string
  56. */
  57. public static function foreign($model, $foreign = null)
  58. {
  59. if ( ! is_null($foreign)) return $foreign;
  60. // If the model is an object we'll simply get the class of the object and
  61. // then take the basename, which is simply the object name minus the
  62. // namespace, and we'll append "_id" to the name.
  63. if (is_object($model))
  64. {
  65. $model = class_basename($model);
  66. }
  67. return strtolower(basename($model).'_id');
  68. }
  69. /**
  70. * Get a freshly instantiated instance of the related model class.
  71. *
  72. * @param array $attributes
  73. * @return Model
  74. */
  75. protected function fresh_model($attributes = array())
  76. {
  77. $class = get_class($this->model);
  78. return new $class($attributes);
  79. }
  80. /**
  81. * Get the foreign key for the relationship.
  82. *
  83. * @return string
  84. */
  85. public function foreign_key()
  86. {
  87. return static::foreign($this->base, $this->foreign);
  88. }
  89. }