has_one_or_many.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php namespace Laravel\Database\Eloquent\Relationships;
  2. use Laravel\Database\Eloquent\Model;
  3. class Has_One_Or_Many extends Relationship {
  4. /**
  5. * Insert a new record for the association.
  6. *
  7. * If save is successful, the model will be returned, otherwise false.
  8. *
  9. * @param Model|array $attributes
  10. * @return Model|false
  11. */
  12. public function insert($attributes)
  13. {
  14. if ($attributes instanceof Model)
  15. {
  16. $attributes->set_attribute($this->foreign_key(), $this->base->get_key());
  17. return $attributes->save() ? $attributes : false;
  18. }
  19. else
  20. {
  21. $attributes[$this->foreign_key()] = $this->base->get_key();
  22. return $this->model->create($attributes);
  23. }
  24. }
  25. /**
  26. * Update a record for the association.
  27. *
  28. * @param array $attributes
  29. * @return bool
  30. */
  31. public function update(array $attributes)
  32. {
  33. if ($this->model->timestamps())
  34. {
  35. $attributes['updated_at'] = new \DateTime;
  36. }
  37. return $this->table->update($attributes);
  38. }
  39. /**
  40. * Set the proper constraints on the relationship table.
  41. *
  42. * @return void
  43. */
  44. protected function constrain()
  45. {
  46. $this->table->where($this->foreign_key(), '=', $this->base->get_key());
  47. }
  48. /**
  49. * Set the proper constraints on the relationship table for an eager load.
  50. *
  51. * @param array $results
  52. * @return void
  53. */
  54. public function eagerly_constrain($results)
  55. {
  56. $this->table->where_in($this->foreign_key(), $this->keys($results));
  57. }
  58. }