本文經授權轉自 PHPHub 社區
使用 Baum 嵌套集合模型來實現 Laravel 模型的無限極分類
說明
大家通常都是使用遞迴實現無限極分類,都知道遞迴效率很低,下面推薦一個 Laravel 的擴充包 etrepat/baum,快速讓你的資料模型支援無限極樹狀層級結構,並且兼顧效率。
更多 嵌套集合模型(Nested set model)的介紹請見:wiki
擴充包的 官方文檔 裡有解釋的篇幅,下面這張圖的也是一個簡單的例子:
file
用例說明
接下來講幾個無限樹狀層級模型的例子。
標籤系統
參考:Laravel Taggable 為你的模型添加打標籤功能一個標籤可以有無數多子標籤,屬於一個父標籤,有多個同輩標籤。
如下面的這顆標籤樹:
$tagTree = [ 'name' => 'RootTag', 'children' => [ ['name' => 'L1Child1', 'children' => [ ['name' => 'L2Child1'], ['name' => 'L2Child1'], ['name' => 'L2Child1'], ] ], ['name' => 'L1Child2'], ['name' => 'L1Child3'], ]];
評論系統
評論的無限極別嵌套,如網易的 跟帖系統。
file
Laravel 有一個評論擴充包支援無限極別嵌套,請見 Slynova-Org/laravel-commentable。
「導覽列」資料模型
管理員後台需要提供「導覽列」自訂功能,樹狀結構導覽列。
file
整合 Baum
etrepat/baum 快速讓你的資料模型支援無限極樹狀層級結構,且兼顧效率。
接下來我們講如何整合。
1. composer 安裝
composer require "baum/baum:~1.1"
2. 增加 provider
修改 config/app.php 檔案,在 providers 數組中添加:
'Baum\Providers\BaumServiceProvider',
此服務提供者註冊了兩個命令:artisan baum, artisan baum.install 。
3. 建立 migration
安裝到已存在的資料模型上:
php artisan baum:install MODEL
然後執行
php artisan migrate
關於 migration 的欄位介紹
- parent_id: 父節點的 id
- lft: 左邊索引值
- rgt: 右邊索引值
- depth: 層級深度
下面是個例子:
class Category extends Migration { public function up() { Schema::create('categories', function(Blueprint $table) { $table->increments('id'); // 這四行代碼 $table->integer('parent_id')->nullable(); $table->integer('lft')->nullable(); $table->integer('rgt')->nullable(); $table->integer('depth')->nullable(); $table->string('name', 255); $table->timestamps(); }); }}
4. 配置資料模型
繼承 Baum\Node
class Category extends Baum\Node {}
繼承後有這些屬性可以重寫:
class Category extends Baum\Node { protected $table = 'categories'; // 'parent_id' column name protected $parentColumn = 'parent_id'; // 'lft' column name protected $leftColumn = 'lidx'; // 'rgt' column name protected $rightColumn = 'ridx'; // 'depth' column name protected $depthColumn = 'nesting'; // guard attributes from mass-assignment protected $guarded = array('id', 'parent_id', 'lidx', 'ridx', 'nesting');}
至此整合成功。
使用
引用:https://phphub.org/topics/2123
整合 etrepat/baum 讓標籤具備從屬關係。
$root = Tag::create(['name' => 'Root']);// 建立子標籤$child1 = $root->children()->create(['name' => 'Child1']);$child = Tag::create(['name' => 'Child2']);$child->makeChildOf($root);// 批量構建樹$tagTree = [ 'name' => 'RootTag', 'children' => [ ['name' => 'L1Child1', 'children' => [ ['name' => 'L2Child1'], ['name' => 'L2Child1'], ['name' => 'L2Child1'], ] ], ['name' => 'L1Child2'], ['name' => 'L1Child3'], ]];Tag::buildTree($tagTree);
更多關聯操作請查看:etrepat/baum 。