GithubHelp home page GithubHelp logo

gazsp / baum Goto Github PK

View Code? Open in Web Editor NEW

This project forked from unikent/baum

129.0 129.0 39.0 818 KB

Baum is an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM.

License: MIT License

PHP 99.96% Shell 0.04%

baum's People

Contributors

beingtomgreen avatar bmitch avatar booomerang avatar ceejayoz avatar ctf0 avatar danwithams7d avatar daxborges avatar dirkpostma avatar dzcpy avatar etrepat avatar gazsp avatar gerp avatar gjmh-unikent avatar grahamcampbell avatar ignaciogc avatar it-can avatar james2037 avatar jamesguthrie avatar joshuadoshua avatar mpociot avatar pawel-damasiewicz avatar poing avatar robmeijer avatar superbuba avatar surt avatar tasarsu avatar tomkita avatar vinicius73 avatar weareredrobot avatar ziadoz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

baum's Issues

[ReflectionException] Class path.database does not exist

Hi! Thanks for forking this and fixing things. I'm getting a weird issue when trying to install this package with Lumen:

php artisan baum:install MODEL

this error is thrown:

[ReflectionException] Class path.database does not exist

Setup everything correctly AFAIK, (composer require, added service provider, etc). What could cause this?

Time to create a new repo?

A forked repo isn't searchable on github, and since it's (almost) 2 years since this fork was created it might be a good idea to create a new repo.

What do you think?

new item adding issue

if try to add a new tree to database using buildTree() method and the tree has left and right but not id , it will change new item's and its parent's left and right by itself.
i think this job should be done only when there are no left and right attributes, because there are jquery plugins such as nestedSortable that do this job perfectly at client side ,so performing it at server side for second time will disarrange menu order

example:
comments are values after saving in database using buildTree method

 $menu_cc = [
        [ 'id' => 1, 'parent_id' => null, 'left' => 1, 'right' => 4//8, 'name' => 'r1' ],
         [ 'id' => 2, 'parent_id' => 1, 'left' => 4 , 'right' => 5, 'name' => 'm2'] 
        [ 'id' => null, 'parent_id' => 1, 'left' => 2//6 , 'right' => 3//7, 'name' => 'm3'] 
      ];

laravel 7 no migration file creation

Hello ,๐Ÿ˜„
Just for information ,the php command artisan:
make:baum {model}
create model file but it does not create a migration file automatically under laravel 7

Support for changing connection.

I'm currently having an issue where I change the connection in the model I have that extends the Node class and call the rebuild() method.

When rebuilding it seems to always use the default connection even after I've set the connection on my model. Something like:

$this->myModelThatExtendsNode->setConnection('foobar');
$this->myModelThatExtendsNode->rebuild();

Since my default database connection is not where the table for the model is I get an error like SQLSTATE[42S02]: Base table or view not found: 1146 Table 'default.table_for_my_model_that_extends_node'

I think the reason for this is inside the rebuild() method a new static is created in the constructor for SetBuilder and that new static has the database connection set to the default DB.

I can try to put together a fix but wanted to see if anyone else has run into this and has any other suggestions/

Performance optimisation with Composite Index

UPDATE/INFORMATION

After the creation of a compound index
I saw my performance greatly implied for the cost of a slightly slower insertion due to the reconstruction of the index but considering the size of the nested data I am a big winner in terms of performance: Index

$table->index(['id', 'lft', 'rgt']);

Too much data causes updates to fail

When the data is too much (millions of data), it can report insufficient memory, can add data to judge, when the data amount is large enough, do not use one-time update

Limit children

How to limit number children's by level, for example one parent only have two children and if have new children save in new level?

Invalid Tree

Is there a way to reset the tree?

  • i removed all LFT, RGT values then run the rebuild(), but still invalid.
  • i checked all parent_id exists
  • no parent_id is null

anymore to check, why tree stil invalid?

thanks

Zero value parent_id instead of null values

Currently, parent_ids must be null to work with this package. In my case, root level nodes have a value of 0, to denote a root level node.

I've taken a look at the code, and it'd be a matter of changing a few queries to add an additional where clause to account for zero values. Is this something that others may need?

Issue with custom primary keys

When using a custom primary key in a model

protected $primaryKey = 'reference';

and the following migration

        $table->string('reference', 20)->primary();
        $table->string('parent_id', 20)->nullable();
        $table->integer('lft')->nullable();
        $table->integer('rgt')->nullable();
        $table->integer('depth')->nullable();

The following:

    $things = [
          ['reference' => 'One'],
          [
               'reference' => 'Two',
               'children' => [
                    ['reference' => 'TwoDotOne'],
                    ['reference' => 'TwoDotTwo']
                 ]
          ],
          ['reference' => 'Three']
     ];
     App\Thing::buildTree($things);

results in a "No query results for model" Error, triggered by the $self->reload() in Node@setDepth.

I guess this is because we're reloading before the new model is persisted?

laravel 7

Hello,
I come from python/django and we have the excellent mptt https://github.com/django-mptt/django-mptt for tree management. I'm currently working on a laravel project where I have to integrate the equivalent, I have a lot of data to save on the tree I found the library: https://github.com/lazychaser/laravel-nestedset, but this one is horrible in terms of performance, it's not very user friendly (don't integrate the depth in the database, even after 50 requests ...., especially as it could solve some of the problems). After several researches the Baum library seems to me the closest to what I need in terms of quality and performance. Now I could see that it is not available for laravel 7, will you adapt it for laravel 7 ?
I could see on this post etrepat#332 that @mkwsra has been asking for a traction for a while couldn't there be a work between you ?
Thank you in advance

Overwrite reOrderBy to accept RAND()?

I've tried every way to get random siblings using reOrderBy and the inRandomOrder in the laravel framework. Is it possible to query in random because i don't want to random a massive collection.

Updating node updated_at causes unwanted side-effects

When I want to touch the timestamp of a nested Model it looses it's depth.

I have a nested Page model that has a relationship with a Content model.
When I update the Content model I want to touch the updated_at timestamp of the Page model.
This all works fine with protected $touches = ['page']; in the Content model, but as a bonus I get a set of extra queries that also set the depth off the Page model to zero.

-
UPDATE `contents` set `fields` = '{\"leader\":[{\"file\":\"2\",\"description\":\"\"}],\"about_titel\":\"\",\"about_tekst_1\":\"\",\"about_tekst_2\":\"\",\"contact_titel\":\"\",\"contact_tekst\":\"\"}', `updated_at` = '2016-09-29 23:52:45' WHERE `id` = '129'
UPDATE `pages` set `updated_at` = '2016-09-29 23:52:45' WHERE `pages`.`id` = '118'
SELECT * FROM `pages` WHERE `pages`.`id` = '118' LIMIT 1
SELECT * FROM `pages` WHERE `pages`.`id` = '118' LIMIT 1
SELECT max(`rgt`) as aggregate FROM `pages`
SELECT * FROM `pages` WHERE `pages`.`id` = '118' LIMIT 1
UPDATE `pages` set `depth` = '0', `updated_at` = '2016-09-29 23:52:45' WHERE `id` = '118' ORDER BY `pages`.`lft` ASC
1.060 m

Is there some kind of event that triggers these last 5 queries?

Get descendants of multiple nodes

I'm struggling everywhere to accomplish this. I need to have all the descendants of multiple nodes as: Category::whereIn('id', [<ids>])->getDescendantsAndSelf()

Load nested set by default in Laravel Relation definition

Thanks so much for taking this project over!!

Is there a way to eager load a nested relationship using Laravel's relationship definitions instead of calling ->toHierarchy()?

i.e.

class Post extends Model
{
    public function categories()
    {
        return $this->hasManyRootsWithDescendants(Category::class);
    }
}

to return a nested set of categories

If this is a feature request I'd be glad to take a look Or is there a better way to load a nested set by default?

Laravel 5.5 Compatibility Issues?

I see that full support for Laravel 5.5 is in progress, but in the meantime, I'm using Baum 1.1 and it seems to be functioning just fine. I'm curious as to why 1.1 is only specifying 5.2 - 5.4 as supported. Are there known issues in 5.5?

Wrong rgt-value when creating child node on PHP 7.2

Wrong rgt-value when creating child node on PHP 7.2

I have this test:

  /** @test **/
    public function store_category()
    {
        // Arrange
        $root = factory(\App\Category::class)->create( ['name' => 'Root', 'depth' => 0]);
    
        // Act
        $response = $this->actingAsAdmin('api')
        ->json('POST', $this->endpoint, [
            'name' => 'New Category',
            'parent_id' => $root->id,
        ]);
    
        // Assert
        $response->assertStatus(200);
        $response->assertJson([
            'tree' => [
                'root' => true,
                'name' => 'Root',
                'children' => [
                    [
                    'name'  => 'New Category',
                    'lft'   => 2,
                    'rgt'   => 3
                    ]
                ]
            ]
        ]);

        $this->assertDatabaseHas('categories', [
            'name' =>  'New Category',
            'slug' =>  'new-category',
            'lft'  =>  2,
            'rgt'  =>  3
        ]);
        $this->assertDatabaseHas('categories', [
            'name' =>  'Root',
            'lft'  =>  1,
            'rgt'  =>  4
        ]);
    }

This works on PHP 7.0 and PHP 7.1 but fails with PHP 7.2

To get the test to pass on PHP 7.2 the last assertion (the one checking the root in the database) has to be changed to below

        $this->assertDatabaseHas('categories', [
            'name' =>  'Root',
            'lft'  =>  1,
            'rgt'  =>  3
        ]);

The actual store function in my app

    public function store(CreateCategoryRequest $request)
    {
        $parent = $request->input('parent_id');
        $category = new Category;
        $category->fill($request->all());
        $category->save();
        $category->makeChildOf($parent);

        return $this->categoryTree($request, $category);
    }

dynamically change the column values

Hi I have a special case where I need the left, right, parent, depth columns to be mapped to other columns in the same table dynamically to get two different tree structures. I tried setting the column properties to custom values as the first step of my experiment but it seems even if I changed the column names in the extended model it still referring the old columns and its not working. What I need actually trying to achieve is to get two types of nested set based on two specific columns say parent_id and sponsor_id etc. Hope you guys have some solutions.
Thanks

how to get hierarchy with relations?

Thanks for continuing the repo!

I can't seem to get the complete hierarchy tree with the relations intact.

    $tree = Group::where('id', '=', $id)
    ->with(['users')
    ->first()
    ->getDescendantsAndSelf()
    ->toHierarchy();

The tree is written out but the users aren't there.

Looks like i have a corrupted tree

I'm using the old library. I'm thinking it would be better to post my issue here since this repo is being maintained. There is a problem on the parent node because lft column is bigger than rgt column

ss2

Also this one. The parent_id is 215 but lft and rgt is not within the parent's lft and rgt

ss3

I hope someone could help me how to fix this. Also this parent node(215) is the last node in the tree. There are no problems in other nodes. Only this one which is the last one.

PHP 7.1 error

This is the error I get on Laravel 5.5 and PHP 7.1:
error

remove inheritance, use Trait

I am interested in using a version of Baum based on Traits. Baum looks well-featured, but we cannot use it by extending from it, because that would break our architecture.

At first glance, I don't really see a blocking issue to introduce Traits. In essence, all Baum\Node code should be moved into a separate Trait. You can then have Baum\Node use that trait, to provide backwards compatibility. If testing with instanceof is an issue, a Node-interface can be created to test on that interface.

In short, some refactoring is necessary to achieve the following pattern:

namespace Baum;

interface NodeInterface {
    // method signatures from Baum\Node
}

trait NodeTrait {
    // implementation from Baum\Node
}

// only necessary for BC
abstract class Node implements NodeInterface {
    use NodeTrait;
}

I'm not really in a position to assess the amount of work involved, but it seems like a straightforward refactoring. And I do not see any drawbacks, as this will be BC and makes the library more flexible in use.

If you're open to my proposed change, I can do the modifications and create a PR.

Returning tree with ancestors collection for each node, like breadcrumbs

Hello.

First of all, thank you for continuing the work on this package. Having implement a nested set library from scratch in the past, it's great to rely on a better thought out and tested package.

I'm struggling here trying to return the ancestors along with each node on a nested set. For example, each result for the descendantsAndSelf() method would have a sub collection with its full path to the root node represented by the ancestors() method. This would be extremely useful to return the breadcrumbs for each node, for example. Something that could be chained like descendantsAndSelf()->withAncestors().

Doing this with a loop after returning the main query is super simple, but I stumble upon a n+1 problem. I need to solve this in a way that can rely on eager loading and be processed with the main query.

Any pointers or suggestions?

Thank you in advance,

How to get all children with where clause

In my project, i need to retrieve all of its children & nested children of a parent. But i want to get children with clause: where is_published= 1 (is activated) because there are some inactive children is_published= 0
But i did not found any solutions. I'm really confused now :(
@gazsp please help me, thanks

Looking for maintainers

Hi all.

I've moved on to other things, and am not actively using or developing Baum at the moment. Is anybody interested in becoming the main package maintainer? Preferably someone who is actively using the package in a Laravel 5.8 app...

CI builds are broken, and the next version needs releasing to Packagist once everything has been cleaned up with unit tests / CI verified as working.

Cheers,
Gaz.

L5.6 baum:install issues

ver dev-feature/2.0
When run "php artisan baum:install" command .
will get the error
Class 'Baum\Console\BaumCommand' not found .
( Providers/BaumServiceProvider.php:46 )

Is this package development still in progress??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.