phpvms/app/Models/Traits/ReferenceTrait.php

51 lines
1015 B
PHP
Raw Normal View History

<?php
namespace App\Models\Traits;
/**
* Trait ReferenceTrait
2018-08-27 00:40:04 +08:00
*
* @property \App\Interfaces\Model $ref_model
* @property mixed $ref_model_id
*/
trait ReferenceTrait
{
/**
* @param \App\Interfaces\Model $object
2018-08-27 00:40:04 +08:00
*
* @return self
*/
public function referencesObject($object)
{
$this->ref_model = \get_class($object);
$this->ref_model_id = $object->id;
$this->save();
return $this;
}
/**
* Return an instance of the object or null
2018-08-27 00:40:04 +08:00
*
* @return \App\Interfaces\Model|null
*/
public function getReferencedObject()
{
if (!$this->ref_model || !$this->ref_model_id) {
2018-08-27 00:40:04 +08:00
return;
}
if ($this->ref_model === __CLASS__) {
return $this;
}
try {
2018-08-27 00:40:04 +08:00
$klass = new $this->ref_model();
$obj = $klass->find($this->ref_model_id);
return $obj;
} catch (\Exception $e) {
2018-08-27 00:40:04 +08:00
return;
}
}
}