has_one.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php namespace Laravel\Database\Eloquent\Relationships;
  2. class Has_One extends Has_One_Or_Many {
  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. * Initialize a relationship on an array of parent models.
  14. *
  15. * @param array $parents
  16. * @param string $relationship
  17. * @return void
  18. */
  19. public function initialize(&$parents, $relationship)
  20. {
  21. foreach ($parents as &$parent)
  22. {
  23. $parent->relationships[$relationship] = null;
  24. }
  25. }
  26. /**
  27. * Match eagerly loaded child models to their parent models.
  28. *
  29. * @param array $parents
  30. * @param array $children
  31. * @return void
  32. */
  33. public function match($relationship, &$parents, $children)
  34. {
  35. $foreign = $this->foreign_key();
  36. $dictionary = array();
  37. foreach ($children as $child)
  38. {
  39. $dictionary[$child->$foreign] = $child;
  40. }
  41. foreach ($parents as $parent)
  42. {
  43. if (array_key_exists($key = $parent->get_key(), $dictionary))
  44. {
  45. $parent->relationships[$relationship] = $dictionary[$key];
  46. }
  47. }
  48. }
  49. }