search
HomePHP FrameworkThinkPHPThe use of unlimited categories in ThinkPHP

The example in this article shows how ThinkPHP auto-fills to achieve infinite classification. It is one of the common functions of ThinkPHP and is of great practical value. Now I will share the complete example with you for your reference.

The use of unlimited categories in ThinkPHP

Use of ThinkPHP unlimited classification

The specific implementation steps are as follows (this article uses version 3.1.3 of the TP framework):

(Recommended tutorial: thinkphp tutorial)

Step one: The table aoli_cate is as shown below

CREATE TABLE `fenlei` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) DEFAULT NULL COMMENT '父id',
  `pid` int(255) NOT NULL COMMENT '名字',
  `path` varchar(20) DEFAULT NULL,//path字段是给数据排序用
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
insert into fenlei(id,name,pid,path) values
(1,’新闻’,0,’0’),
(2,’中国新闻’,1,’0-1’),//path 最后一个数据是排序用的
(3,’美国新闻’,1,’0-1’),
(4,’北京新闻’,2,’0-1-2’),
(5,’华盛顿新闻’,3,’0-1-3’),
(6,’日本新闻’,1,’0-1’);

The use of unlimited categories in ThinkPHP

Step 2: action part

aoli/Home/Lib/Action/CataAction.class.php file is as follows:

<?php
class CateAction extends Action{
  function index(){
    //实例化cate
    $cate=M(&#39;cate&#39;);
    //获取数据
    //将path和id连接起来,组合成为bpath数组
    $list=$cate->field("id,name,pid,path,concat(path,&#39;-&#39;,id) as bpath")->order(&#39;bpath&#39;)->select();
    foreach($list as $key=>$value){
       //在查询获取的数组里面增加一个&#39;count&#39;数组;
       //统计bpath字段的字符串个数,并赋值给&#39;count&#39;数组。
       $list[$key][&#39;count&#39;]=count(explode(&#39;-&#39;,$value[&#39;bpath&#39;]));
    }
    //展示数据
    $this->assign(&#39;alist&#39;,$list);
    $this->display();  
  }
  //添加栏目
  function add(){
    //实例化CateModel类
    $cate=new CateModel();
    //如果从CateModel模型接受数据成功
    if($vo=$cate->create()){
      //执行添加
      if($cate->add()){
        $this->success(&#39;添加栏目成功&#39;);  
      }else{
        $this->error(&#39;添加栏目失败&#39;);  
      }
      //dump($vo);  
    }else{
      //返回错误信息
      $this->error($cate->getError());  
    }
  }
}
?>

Step 3: Model part

aoli/Home/Lib/Model/CataModel.class.php file is as follows:

<?php
class CateModel extends Model{//对应数据库中的表aoli_cate
  //在Model类定义 $_auto 属性,可以完成数据自动处理功能,用来处理默认值、数据过滤以及其他系统写入字段。$_auto属性是由多个填充因子组成的数组。
  protected $_auto=array(
    //示例   
    //对name字段在新增的时候回调getName方法
    //array(&#39;name&#39;,&#39;getName&#39;,1,&#39;callback&#39;),
    //&#39;path&#39;填充字段
    //&#39;tclm&#39;回调函数
    // 3 新增数据和更新数据的时候都处理
    // callback :回调方法 ,表示填充的内容是一个当前模型的方法
    array(&#39;path&#39;,&#39;tclm&#39;,3,&#39;callback&#39;),  
  ); 
   //回调函数
  function tclm(){
    //如果pid存在,就转成整形,不存在就赋值0,表示是根目录
    $pid=isset($_POST[&#39;pid&#39;])?(int)$_POST[&#39;pid&#39;]:0;
    //可以查看pid
    //echo ($pid);
    //如果是根目录,就是在select表单没有选任何值提交的时候
    if($pid==0){
      //
      $data=0;
    }else{
      //如果id和pid相等
      $list=$this->where("id=$pid")->find();
      //把回调值$data赋值
      $data=$list[&#39;path&#39;].&#39;-&#39;.$list[&#39;id&#39;];//子类的path为父类的path加上父类的id
    }
    //回调值
    return $data;  
  }
}
?>

Step 4: viewView part

<!--提交到本类的add方法-->
<form action="__URL__/add" method="post">
//size="20"可以将select 框变大
 请选择父级栏目:<select name="pid" size="20">
         //value="0"表示为根目录
         <option value="0">根栏目</option>
         //展示数据
         <volist name="alist" id="vo">
          <option value="{$vo[&#39;id&#39;]}">
            <php>
              <!--以字段count统计出来的,path字段里面含的字符串来做总数-->
              for($i=0;$i<$vo[&#39;count&#39;];$i++){
                //在值前面添加空格
                echo  &#39;;  
              }
            </php>
            //输出值
            {$vo[&#39;name&#39;]}
          </option>
         </volist>
        </select><br />
 新的栏目名称:<input type="text" name="name" /><br />
 <input type="submit" value="添加栏目" />
</form>

The above is the detailed content of The use of unlimited categories in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),