Last active
February 19, 2017 22:00
-
-
Save liam-wiltshire/e4a2b4ce57dc5768c87a7f68b9becbd5 to your computer and use it in GitHub Desktop.
This file contains 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 App\Models; | |
use LogicException; | |
use Illuminate\Database\Eloquent\Relations\Relation; | |
use Illuminate\Database\Eloquent\Collection; | |
abstract class JitModel extends \Illuminate\Database\Eloquent\Model | |
{ | |
protected $parentCollection = null; | |
/** | |
* Load a relationship based on the method provided | |
* | |
* @param string $method The method name to load | |
* | |
* @return mixed | |
*/ | |
public function getRelationshipFromMethod($method) | |
{ | |
$relations = $this->$method(); | |
if ($this->parentCollection && count($this->parentCollection) > 1) { | |
$this->parentCollection->load($method); | |
} | |
if (!$relations instanceof Relation) { | |
throw new LogicException('Relationship method must return an object of type ' | |
. 'Illuminate\Database\Eloquent\Relations\Relation'); | |
} | |
return $this->relations[$method] = $relations->getResults(); | |
} | |
/** | |
* Create a new Eloquent Collection instance. | |
* | |
* @param array $models Array of models to create collection from | |
* | |
* @return \Illuminate\Database\Eloquent\Collection | |
*/ | |
public function newCollection(array $models = []) | |
{ | |
$collection = new Collection($models); | |
foreach ($collection as &$model) { | |
$model->parentCollection = $collection; | |
} | |
return $collection; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment