laravel-adjacency-list icon indicating copy to clipboard operation
laravel-adjacency-list copied to clipboard

Automatic path without model ID

Open maximesahagian opened this issue 2 years ago • 8 comments

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

maximesahagian avatar Sep 15 '22 09:09 maximesahagian

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.

staudenmeir avatar Sep 15 '22 10:09 staudenmeir

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

maximesahagian avatar Sep 15 '22 14:09 maximesahagian

I'll see if there's a solution for that.

staudenmeir avatar Sep 15 '22 16:09 staudenmeir

Which database engine are you using?

staudenmeir avatar Sep 15 '22 16:09 staudenmeir

I'm using Mysql @staudenmeir

maximesahagian avatar Sep 16 '22 08:09 maximesahagian

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.

staudenmeir avatar Sep 16 '22 17:09 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.

Absolutely, it’s to show it in a view

maximesahagian avatar Sep 16 '22 18:09 maximesahagian

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);
}

staudenmeir avatar Sep 17 '22 12:09 staudenmeir