Skip to content

Instantly share code, notes, and snippets.

@alexweissman
Created August 1, 2018 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexweissman/bc01dc485cfb41a2b4f9ca2e9666c68e to your computer and use it in GitHub Desktop.
Save alexweissman/bc01dc485cfb41a2b4f9ca2e9666c68e to your computer and use it in GitHub Desktop.
<?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