Created
August 1, 2018 14:26
-
-
Save alexweissman/bc01dc485cfb41a2b4f9ca2e9666c68e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace UserFrosting\Sprinkle\Site\Database\Concerns; | |
/** | |
* Implements event and linking methods for extended models. | |
* | |
* Set the member variable $auxType in your derived class. | |
*/ | |
trait HasAuxModel | |
{ | |
/** | |
* The "booting" method of the model. | |
* | |
* @return void | |
*/ | |
protected static function bootHasAuxModel() | |
{ | |
/** | |
* Create a new aux model if necessary, and save the associated aux every time. | |
*/ | |
static::saved(function ($super) | |
{ | |
// Link subtype object, creating it if it doesn't already exist | |
// and setting the id from the parent model | |
$super->linkAuxModel(); | |
// Save related child object | |
if ($super->auxType) { | |
$super->aux->save(); | |
} | |
}); | |
} | |
/** | |
* Required to be able to access additional relationships in Twig without needing to do eager loading. | |
* @see http://stackoverflow.com/questions/29514081/cannot-access-eloquent-attributes-on-twig/35908957#35908957 | |
*/ | |
public function __isset($name) | |
{ | |
if (in_array($name, [ | |
'aux' | |
])) { | |
return true; | |
} else { | |
return parent::__isset($name); | |
} | |
} | |
/** | |
* Relationship for interacting with aux model. | |
*/ | |
public function aux() | |
{ | |
return $this->hasOne($this->auxType, 'id'); | |
} | |
/** | |
* If this instance doesn't already have a related aux model (either in the db on in the current object), then create one | |
*/ | |
protected function linkAuxModel() | |
{ | |
if ($this->auxType) { | |
$this->createAuxModelIfNotExists(); | |
$this->setAuxModelPrimaryKey(); | |
} | |
} | |
/** | |
* Create and attach aux subtype model if it doesn't exist. | |
*/ | |
protected function createAuxModelIfNotExists() | |
{ | |
if (count($this->aux)) { | |
return; | |
} | |
// Needed to immediately hydrate the relation. It will actually get saved in the bootHasAuxModel method. | |
$this->setRelation('aux', new $this->auxType); | |
} | |
/** | |
* Copy the parent id to the aux model, if the parent has an id at this point but the aux doesn't | |
*/ | |
protected function setAuxModelPrimaryKey() | |
{ | |
if (isset($this->id) && !isset($this->aux->id)) { | |
$this->aux->id = $this->id; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment