2018-04-02 07:02:12 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Models\Traits;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Trait ReferenceTrait
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-02 07:02:12 +08:00
|
|
|
* @property \App\Interfaces\Model $ref_model
|
2018-04-02 11:26:20 +08:00
|
|
|
* @property mixed $ref_model_id
|
2018-04-02 07:02:12 +08:00
|
|
|
*/
|
|
|
|
trait ReferenceTrait
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param \App\Interfaces\Model $object
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-02 07:02:12 +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
|
|
|
*
|
2018-04-02 07:02:12 +08:00
|
|
|
* @return \App\Interfaces\Model|null
|
|
|
|
*/
|
|
|
|
public function getReferencedObject()
|
|
|
|
{
|
2018-04-02 11:26:20 +08:00
|
|
|
if (!$this->ref_model || !$this->ref_model_id) {
|
2018-08-27 00:40:04 +08:00
|
|
|
return;
|
2018-04-02 11:26:20 +08:00
|
|
|
}
|
2018-04-02 07:02:12 +08:00
|
|
|
|
2018-04-02 11:26:20 +08:00
|
|
|
if ($this->ref_model === __CLASS__) {
|
|
|
|
return $this;
|
2018-04-02 07:02:12 +08:00
|
|
|
}
|
|
|
|
|
2018-04-02 11:26:20 +08:00
|
|
|
try {
|
2018-08-27 00:40:04 +08:00
|
|
|
$klass = new $this->ref_model();
|
2018-04-02 11:26:20 +08:00
|
|
|
$obj = $klass->find($this->ref_model_id);
|
|
|
|
return $obj;
|
|
|
|
} catch (\Exception $e) {
|
2018-08-27 00:40:04 +08:00
|
|
|
return;
|
2018-04-02 11:26:20 +08:00
|
|
|
}
|
2018-04-02 07:02:12 +08:00
|
|
|
}
|
|
|
|
}
|