Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Eloquent\Traits;
- trait Delegatable
- {
- public function getAttribute($key)
- {
- $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
- foreach ($delegates as $relationKey => $fields) {
- if (in_array($key, $fields) === true) {
- $foreign = $this->{$relationKey};
- return $foreign ? $foreign->getAttribute($key) : null;
- }
- }
- return parent::getAttribute($key);
- }
- /**
- * {@inheritdoc}
- */
- public function save(array $options = [])
- {
- $result = parent::save($options);
- if ($result === true) {
- $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
- foreach ($delegates as $relationKey => $fields) {
- $foreign = $this->{$relationKey};
- if (($foreign !== null) && ($foreign->exists === false)) {
- $relation = $this->{$relationKey}();
- $model = $relation->getQuery()->getModel();
- $foreign->setAttribute($model->getP, 1);
- $foreign->save();
- }
- }
- }
- return $result;
- }
- public function setAttribute($key, $value)
- {
- $delegates = property_exists($this, 'delegate') ? $this->delegate : [];
- foreach ($delegates as $relationKey => $fields) {
- if (in_array($key, $fields) === true) {
- $foreign = $this->{$relationKey};
- // automatically create a new instance of the foreign object if it doesn't exist
- if ($foreign === null) {
- $relation = $this->{$relationKey}();
- $model = $relation->getQuery()->getModel();
- $foreign = $model->newInstance();
- $this->setRelation($relationKey, $foreign);
- }
- return $foreign->setAttribute($key, $value);
- }
- }
- return parent::setAttribute($key, $value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement