Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. <?php
  2. namespace App\Eloquent\Traits;
  3.  
  4. trait Delegatable
  5. {
  6.  
  7. public function getAttribute($key)
  8. {
  9. $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
  10.  
  11. foreach ($delegates as $relationKey => $fields) {
  12. if (in_array($key, $fields) === true) {
  13. $foreign = $this->{$relationKey};
  14. return $foreign ? $foreign->getAttribute($key) : null;
  15. }
  16. }
  17.  
  18. return parent::getAttribute($key);
  19. }
  20.  
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function save(array $options = [])
  25. {
  26. $result = parent::save($options);
  27.  
  28. if ($result === true) {
  29. $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
  30.  
  31. foreach ($delegates as $relationKey => $fields) {
  32. $foreign = $this->{$relationKey};
  33.  
  34. if (($foreign !== null) && ($foreign->exists === false)) {
  35. $relation = $this->{$relationKey}();
  36. $model = $relation->getQuery()->getModel();
  37.  
  38. $foreign->setAttribute($model->getP, 1);
  39. $foreign->save();
  40. }
  41. }
  42. }
  43.  
  44. return $result;
  45. }
  46.  
  47. public function setAttribute($key, $value)
  48. {
  49. $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
  50.  
  51. foreach ($delegates as $relationKey => $fields) {
  52. if (in_array($key, $fields) === true) {
  53. $foreign = $this->{$relationKey};
  54.  
  55. // automatically create a new instance of the foreign object if it doesn't exist
  56. if ($foreign === null) {
  57. $relation = $this->{$relationKey}();
  58. $model = $relation->getQuery()->getModel();
  59. $foreign = $model->newInstance();
  60.  
  61. $this->setRelation($relationKey, $foreign);
  62. }
  63.  
  64. return $foreign->setAttribute($key, $value);
  65. }
  66. }
  67.  
  68. return parent::setAttribute($key, $value);
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement