laravel-nestedset
laravel-nestedset copied to clipboard
withDepth method now working correctly when using nested set as a relation on another model
Hi, depth is not calculated properly when fetching a nested set as a relation on another model. Depth is set to -1 for all records.
This is my case:
I have a model called Codelist. It represents a simple table with id and name. This model has a relationship called options that is actually a nested set.
Codelist.php
class Codelist extends Model {
// ...
public function options()
{
return $this->hasMany(CodelistOption::class, 'codelist_id', 'id')
->withDepth()
;
}
}
CodelistOption.php
use Kalnoy\Nestedset\NodeTrait;
class CodelistOption extends Model {
use NodeTrait;
// ...
}
And here I try to fetch code lists with options (withDepth method is in the relationship method).
Codelist::with('options')->get()
I also use codelist_id as a nested set scope.
What I did is I created my own scope method scopeIncludingDepth that looks like this:
public function scopeIncludeDepth(QueryBuilder $q, String $columns = '*') {
$alias = '_d';
$q->select("codelist_options.{$columns}");
$query = self::selectRaw('count(1) - 1')
->from("codelist_options as {$alias}")
->whereRaw("codelist_options._lft between {$alias}._lft and {$alias}._rgt")
->whereRaw("codelist_options.codelist_id = {$alias}.codelist_id")
->getQuery();
$q->selectSub($query, 'depth');
return $q;
}
but this is just a hack. I would prefer to use withDepth method.