Coder Social home page Coder Social logo

nestablecollection's Introduction

NestableCollection

Software License

A Laravel Package that extends collections to handle nested items following adjacency list model.

Installation

Run composer require typicms/nestablecollection

Usage

The model must have a parent_id attributes :

protected $fillable = [
    'parent_id',
    // …
];

and must use the following trait:

use TypiCMS\NestableTrait;

Now each time you get a collection of that model, it will be an instance of TypiCMS\NestableCollection in place of Illuminate\Database\Eloquent\Collection.

If you want a tree of models, simply call the nest method on a collection ordered by parent_id asc :

Model::orderBy('parent_id')->get()->nest();

Of course you will probably want a position column as well. So you will have to order first by parent_id asc and then by position asc.

Change the name of subcollections

By default, the name of the subcollections is items, but you can change it by calling the childrenName($name) method : For example if you want your subcollections being named children:

$collection->childrenName('children')->nest();

Indented and flattened list

listsFlattened() method generate the tree as a flattened list with id as keys and title as values, perfect for select/option, for example :

[
    '22' => 'Item 1 Title',
    '10' => '    Child 1 Title',
    '17' => '    Child 2 Title',
    '14' => 'Item 2 Title',
]

To use it, first call the nest() method, followed by the listsFlattened() method:

Model::orderBy('parent_id')->get()->nest()->listsFlattened();

By default it will look for a title column. You can send a custom column name as first parameter:

Model::orderBy('parent_id')->get()->nest()->listsFlattened('name');

Four spaces are used to indent by default, to use your own use the setIndent() method, followed by the listsFlattened() method:

Model::orderBy('parent_id')->get()->nest()->setIndent('> ')->listsFlattened();

Results:

[
    '22' => 'Item 1 Title',
    '10' => '> Child 1 Title',
    '17' => '> Child 2 Title',
    '14' => 'Item 2 Title',
]

Nesting a subtree

This package remove items that have missing ancestor, this doesn’t allow you to nest a branch of a tree. To avoid this, you can use the noCleaning() method:

Model::orderBy('parent_id')->get()->noCleaning()->nest();

nestablecollection's People

Contributors

aimalamiri avatar frezno avatar hsharghi avatar izshreyansh avatar nwidart avatar rebeccathedev avatar sdebacker avatar shankhadevpadam avatar tonyrouse 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestablecollection's Issues

Have an error on calling nest()

Method Illuminate\Database\Eloquent\Collection::nest does not exist.
This is the error shown in whoops. I followed the instructions and still i get this error.
I have added the trait in the model still it doesnt work.

<?php

namespace App;

use TypiCMS\NestableTrait;
use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    protected $fillable = [
        'id',
        'parent_id',
        'permission_name',
        'show_name',
    ];
  }

I'm using Laravel 5.6.
The query I called is
return $permissions =Permission::orderBy('parent_id')->get()->nest();
Can you please solve this issue?

After Fresh install query errors

Debian 8
Mysql 8
Php 7.1.x
Thanks for sharing this project...
Have an issue after fresh install pretty much any creation activity such as creating a folder or uploading an image produces this type of error..

SQLSTATE[42S22]: Column not found: 1054 Unknown column '/admin/blocks' OR '/admin/files'

Pointers would be much appreciated..
Thanks

////// Create folder ////
[2018-09-24 19:20:48] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column '/admin/files' in 'field list' (SQL: insert into typicms_files (folder_id, type, name, description, alt_attribute, /admin/files, updated_at, created_at) values (, f, dertui, [], [], , 2018-09-24 19:20:48, 2018-09-24 19:20:48)) {"userId":1,"email":"[email protected]","exception":"[object] (Illuminate\Database\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column '/admin/files' in 'field list' (SQL: insert into typicms_files (folder_id, type, name, description, alt_attribute, /admin/files, updated_at, created_at) values (, f, dertui, [], [], , 2018-09-24 19:20:48, 2018-09-24 19:20:48)) at /var/www/mysk/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column '/admin/files' in 'field list' at /var/www/mysk/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452)
[stacktrace]

/////// create block /////
SQLSTATE[42S22]: Column not found: 1054 Unknown column '/admin/blocks' in 'field list' (SQL: insert into typicms_blocks (name, status, body, /admin/blocks, updated_at, created_at) values (Nonka, {"fr":"0","nl":"0","en":"0"}, {"fr":null,"nl":null,"en":"

Slop</p>"}, , 2018-09-24 19:27:13, 2018-09-24 19:27:13))

Return nest by belongs model

I get my menu items like this. There's a way to get the Menu items and append children to clean up this snippets below.

$menu =  Menu::query()
  ->where('name', 'Main')->first();

$menu->items = MenuItem::orderBy('id')
   ->where('menu_id', '=', $menu->id)
   ->get()
   ->childrenName('children')
   ->nest();

return ResponseBuilder::success([
  'menu' => $menu
]);

Menu

public function items()
 {
      return $this->hasMany(MenuItem::class, 'menu_id');
 }

Problem with `where` clause with `LIKE` in it

I'm using NestableTrait in my model. I want to use where to select some of the rows. My model is Category
Category::where('name', "Clothes"); works fine. But if I want to use it like this:
Category::where('name', 'LIKE', "%Clothes%"); it doesn't have any items in it.
When I use a raw query to get the columns it has some items in it:
collect(DB::select("SELECT * FROM categoriesWHEREname LIKE '%clothes%';"));

Any idea how I can fix this? I would have used the raw query but I want the model's relations as well, and it doesn't make any sense to add the relations by join when I can simply use the model.

Private variables in NestableCollection

I have extended NestableCollection in my application, but I can't access the internal variables in NestableCollection from my extended class because they're private. Could you please make them protected instead so I can use them?

it is not working for diffrent primary key

this one is not working for different primary key suppose my table has primay as pk_id and one table has primary key has id how can i dynamically set the primary key here

Not supporting with Laravel 10

I am getting the following error while installing on laravel 10:

Problem 1
    - Root composer.json requires typicms/nestablecollection ^2.0.1 -> satisfiable by typicms/nestablecollection[2.0.1].
    - typicms/nestablecollection 2.0.1 requires illuminate/database ~9.0 -> found illuminate/database[v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.

Not worked in laravel 6.

Category::orderBy('parent_id')->get()->nest()->setIndent('> ')->listsFlattened();
proc_open(): fork failed - Cannot allocate memory

This code is worked in laravel version below 6, but in 6 it's not working above error occur.

listsFlattened with custom column name

Hello,

I'm trying to get a flattened list of a nestable collection. Though, I'm using the name column.
I can't seem to be able to set that column:

return $this->model->orderBy('parent_id')->get()->listsFlattened(null, 0, [], 'name');

This returns: Cannot pass parameter 3 by reference

When I remove the reference from the 3rd parameter if the listsFlattened method, I only get:

array:3 [▼
  1 => "En Category"
  6 => "Third Categoryyy"
  3 => "Second Category"
]

But even them ->listsFlattened(null, 0, [], 'name') isn't really nice. (lot's of empty parameters).

Though, the table structure is like so:
screen shot 2015-03-24 at 09 51 31

Category id 3 (Second Category) should be under the first category.

So to summarise:

  1. It might be better to have the $column property as first parameter

    public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = '&nbsp;&nbsp;&nbsp;&nbsp;')
  2. Why is the item #3 in the example above not indended ?

Thanks!

Why i should get the weird error.

$categories = Category::orderByRaw('-name ASC')
        ->get()
        ->nest()
        ->listsFlattened('name');
dd($categories);
proc_open(): fork failed - Cannot allocate memory

Nest method changed

Was there a breaking change introduced recently ?

The ->nest() is returning 0 items again. (items are ordered by parent_id, with no changed on this end.)

When running dd($this->items); after line 60 ($this->items = array_values(array_except($this->items, $keysToDelete));) I get an empty array.

Custom name for items

Rather than returning a list of items, allowing a custom name to be chosen would make it more readable and also able to work out the box with other packages.

List all childs of model

Is there any way to use this library for this purpose?
What I want is something like \App\Department::find(12345)->orderBy('parent_id')->get()->nest()->listFlattened('name')

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.