laravel-adjacency-list
laravel-adjacency-list copied to clipboard
Automatic path without model ID
Hello,
I have a problem with the path of my tree. I would like the path to be automatically as such: 1 1.1.1 1.1.2 2 2.1.1 Etc...
But unfortunately I have ID PARENT_ID.PARENT_ID2.ID PARENT_ID.PARENT_ID2.ID ID PARENT_ID.PARENT_ID2.ID Etc...
I don't want the model ID for my path, but just the current automatically generated path, is that possible?
Thank you
Hi @maximesahagian, Which relationship are you using? What does your query look like?
Please share a few sample rows and the paths you are getting at the moment vs. the paths you would like to get.
Thank for your reply @staudenmeir
My request is easy as
$constraint = function ($query) use ($model) {
$query->whereNull('parent_id')->where('model_id', $model->id);
};
$tree = Model::treeOf($constraint)->depthFirst()->get();
And when i try for example $tree->first()->path, the model's ID is returned, but I want to get the path as I asked above, and not the model_id.
For example in my tree i get the parent id = 7 in the DB, and the children with id = 3.
Here is what i get when i foreach $tree and print $treeEntry->path:
- 7
- 7.3
But what i want is:
- 1
- 1.1
Thank you
I'll see if there's a solution for that.
Which database engine are you using?
I'm using Mysql @staudenmeir
What do you want to do with that path? Show it in a view?
I looked into generating the path in SQL and it's probably possible, but the query would be pretty complex. It would be much easier to generate the path in PHP after executing the query.
What do you want to do with that path? Show it in a view?
I looked into generating the path in SQL and it's probably possible, but the query would be pretty complex. It would be much easier to generate the path in PHP after executing the query.
Absolutely, it’s to show it in a view
Try something like this:
$tree = Model::treeOf($constraint)->depthFirst()->get();
$version = [];
$depth = -1;
foreach ($tree as $model) {
if ($model->depth > $depth) {
$version[$model->depth] = 1;
} else {
if ($model->depth < $depth) {
$version = array_slice($version, 0, $model->depth + 1);
}
$version[$model->depth]++;
}
$depth = $model->depth;
$model->version_path = implode('.', $version);
dump($model->version_path);
}