belongs_to.php 2.1 KB

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