Skip to content

Instantly share code, notes, and snippets.

@sjclemmy
Last active August 29, 2015 14:07
Show Gist options
  • Save sjclemmy/f79639ea636eb9e733a0 to your computer and use it in GitHub Desktop.
Save sjclemmy/f79639ea636eb9e733a0 to your computer and use it in GitHub Desktop.
polymorphic Closure Table Extension
<?php
use \Franzose\ClosureTable\Models\Entity as ClosureEntity;
Class PolyClosureModel extends ClosureEntity {
protected $rootKey;
public function getDescendants(array $columns = ['*'])
{
return $this->joinClosureBy('descendant')->get($columns);
}
protected function getRelatedTables($rootElement) {
$modelTypes = \DB::table('content')
->select('content.content_type')
->distinct()
->join('content_closure', 'content.id', '=', 'content_closure.descendant')
->where('content_closure.ancestor','=',$rootElement)
->lists('content_type');
$joins = $this;
foreach ($modelTypes as $type) {
$joins = $joins
->leftJoin('content_'. strtolower($type), function ($join) use ($type) {
$join
->on('content.content_id', '=', 'content_'. strtolower($type).'.id')
->on('content.content_type','=',\DB::raw("'$type'"));
});
}
return $joins;
}
protected function joinClosureBy($column, $withSelf = true)
{
$primary = $this->getQualifiedKeyName();
$closure = $this->closure->getTable();
$ancestor = $this->closure->getQualifiedAncestorColumn();
$descendant = $this->closure->getQualifiedDescendantColumn();
$this->rootKey = $this->getKey();
$query = $this->getRelatedTables($this->rootKey);
switch($column)
{
case 'ancestor':
$query = $query->join($closure, $ancestor, '=', $primary)
->where($descendant, '=', $this->rootKey);
break;
case 'descendant':
$query = $query->join($closure, $descendant, '=', $primary)
->where($ancestor, '=', $this->rootKey);
break;
}
$depthOperator = ($withSelf === true ? '>=' : '>');
$query->where($this->closure->getQualifiedDepthColumn(), $depthOperator, 0);
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment