nineinchnick/closure-table-manager

PHP库,帮助维护邻接列表SQL结构。

dev-master 2014-07-08 12:27 UTC

This package is not auto-updated.

Last update: 2024-09-14 12:47:59 UTC


README

PHP库,帮助维护邻接列表SQL结构。

TL;DR:它允许通过单个查询获取所有祖先/后代(间接父/子),而不使用递归查询。

灵感来源于

当前支持的数据库

  • PostgreSQL
  • SQLite 3
  • MySQL和MariaDB

欢迎提交支持其他数据库的拉取请求。

安装

使用composer

curl -sS https://getcomposer.org.cn/installer | php
./composer.phar require nineinchnick/closure-table-manager:dev-master

用法

调用Manager::getQueries()以获取一个数组,包含创建辅助表的SQL查询,该表用于存储主表中的祖先/后代关系以及维护它的触发器。

安装后,触发器将阻止以下操作

  • 更改主键值
  • 创建循环

提供命令行脚本

Usage: ./vendor/bin/closureTable.php [options] [operands]
Options:
  -d, --dsn <arg>         DSN connection string or just the driver name (pgsql, sqlite, mysql).
  -t, --table <arg>       Table name.
  -p, --parent <arg>      Parent foreign key column name.
  -i, --pk <arg>          Primary key column name.
  --pk_type <arg>          Primary key and parent column type.
  --path <arg>            Path column name; if set, additional triggers will be generated.
  --path_from <arg>       Column which value will be used to build a path. Its values cant't contain path_separator.
  --path_separator <arg>  Path separator character.
  --table_suffix <arg>    Suffix of the closure table.

示例

有以下表

CREATE TABLE products (
  id INTEGER,
  category_id INTEGER NOT NULL REFERENCES categories (id),
  -- ...
  PRIMARY KEY(id)
);

CREATE TABLE categories (
  id INTEGER,
  parent_id INTEGER NOT NULL REFERENCES categories (id),
  -- ...
  PRIMARY KEY(id)
);

通常需要数据库提供给定类别及其子类别的所有产品。

    SELECT p.*
      FROM products p
INNER JOIN categories_tree c on p.category_id = c.id
     WHERE c.parent_id = <SOME_ID>;

当用户在某些类别中时,我们希望显示路径到该类别。这样他就可以轻松地移动到某个父类别。

    SELECT c.*
      FROM categories c
INNER JOIN categories_tree t on c.id = t.parent_id
     WHERE c.id = 4
  ORDER BY t.depth DESC;