belongs_to.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php namespace Laravel\Database\Eloquent\Relationships;
  2. class Belongs_To extends Relationship {
  3. /**
  4. * Get the properly hydrated results for the relationship.
  5. *
  6. * @return Model
  7. */
  8. public function results()
  9. {
  10. return parent::first();
  11. }
  12. /**
  13. * Update the parent model of the relationship.
  14. *
  15. * @param Model|array $attributes
  16. * @return int
  17. */
  18. public function update($attributes)
  19. {
  20. $attributes = ($attributes instanceof Model) ? $attributes->get_dirty() : $attributes;
  21. return $this->model->update($this->foreign_value(), $attributes);
  22. }
  23. /**
  24. * Set the proper constraints on the relationship table.
  25. *
  26. * @return void
  27. */
  28. protected function constrain()
  29. {
  30. $this->table->where($this->base->key(), '=', $this->foreign_value());
  31. }
  32. /**
  33. * Initialize a relationship on an array of parent models.
  34. *
  35. * @param array $parents
  36. * @param string $relationship
  37. * @return void
  38. */
  39. public function initialize(&$parents, $relationship)
  40. {
  41. foreach ($parents as &$parent)
  42. {
  43. $parent->relationships[$relationship] = null;
  44. }
  45. }
  46. /**
  47. * Set the proper constraints on the relationship table for an eager load.
  48. *
  49. * @param array $results
  50. * @return void
  51. */
  52. public function eagerly_constrain($results)
  53. {
  54. $keys = array();
  55. // Inverse one-to-many relationships require us to gather the keys from the
  56. // parent models and use those keys when setting the constraint since we
  57. // are looking for the parent of a child model in this relationship.
  58. foreach ($results as $result)
  59. {
  60. $keys[] = $result->{$this->foreign_key()};
  61. }
  62. $this->table->where_in($this->model->key(), array_unique($keys));
  63. }
  64. /**
  65. * Match eagerly loaded child models to their parent models.
  66. *
  67. * @param array $children
  68. * @param array $parents
  69. * @return void
  70. */
  71. public function match($relationship, &$children, $parents)
  72. {
  73. $foreign = $this->foreign_key();
  74. foreach ($children as &$child)
  75. {
  76. if (array_key_exists($child->$foreign, $parents))
  77. {
  78. $child->relationships[$relationship] = $parents[$child->$foreign];
  79. }
  80. }
  81. }
  82. /**
  83. * Get the value of the foreign key from the base model.
  84. *
  85. * @return mixed
  86. */
  87. public function foreign_value()
  88. {
  89. return $this->base->get_attribute($this->foreign);
  90. }
  91. }