创建一个树类
让我们继续完善我们的博客应用程序,想象我们想要分类我们的文章。 我们想要对类别进行排序,为此,我们将使用Tree行为来帮助我们组织类别。
但首先,我们需要修改我们的表。
我们将使用migrations插件在我们的数据库中创建一个表。 如果您的数据库中已有文章表,请将其清除。
现在打开你的应用程序的composer.json文件。 通常你会看到migrations插件已经在require
下。 如果没有,请通过执行以下命令添加:
composer require cakephp/migrations:~1.0
迁移插件现在将位于应用程序的插件文件夹中。 另外,添加Plugin::load('Migrations');
到您的应用程序的bootstrap.php文件。
加载插件后,运行以下命令创建迁移文件:
bin/cake bake migration CreateArticles title:string body:text category_id:integer created modified
<?php
use Migrations\AbstractMigration;
class CreateArticles extends AbstractMigration
{
public function change()
{
$table = $this->table('articles');
$table->addColumn('title', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('body', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('category_id', 'integer', [
'default' => null,
'limit' => 11,
'null' => false,
]);
$table->addColumn('created', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('modified', 'datetime', [
'default' => null,
'null' => false,
]);
$table->create();
}
}
categories
表。 如果需要指定字段长度,可以在字段类型的括号内进行,即:
bin/cake bake migration CreateCategories parent_id:integer lft:integer[10] rght:integer[10] name:string[100] description:string created modified
<?php
use Migrations\AbstractMigration;
class CreateCategories extends AbstractMigration
{
public function change()
{
$table = $this->table('categories');
$table->addColumn('parent_id', 'integer', [
'default' => null,
'limit' => 11,
'null' => false,
]);
$table->addColumn('lft', 'integer', [
'default' => null,
'limit' => 10,
'null' => false,
]);
$table->addColumn('rght', 'integer', [
'default' => null,
'limit' => 10,
'null' => false,
]);
$table->addColumn('name', 'string', [
'default' => null,
'limit' => 100,
'null' => false,
]);
$table->addColumn('description', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('created', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('modified', 'datetime', [
'default' => null,
'null' => false,
]);
$table->create();
}
}
现在已创建迁移文件,您可以在创建表之前对其进行编辑。 我们需要将parent_id
字段的'null' => false
更改为'null' => true
,因为顶级类别的parent_id
为null。
运行以下命令创建表:
bin/cake migrations migrate
随着我们的表设置,我们现在可以专注于分类我们的文章。
我们假设你已经有第2部分的文件(表,控件和模板的文章)。所以我们只是添加对类别的引用。
我们需要将文章和类别表关联起来。 打开src / Model / Table / ArticlesTable.php文件并添加以下内容:
// src/Model/Table/ArticlesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
// Just add the belongsTo relation with CategoriesTable
$this->belongsTo('Categories', [
'foreignKey' => 'category_id',
]);
}
}
通过启动Bake命令创建所有文件:
bin/cake bake model Categories
bin/cake bake controller Categories
bin/cake bake template Categories
bin/cake bake all Categories
▲ 注意: 如果你在Windows上,记得使用\而不是/。
echo $this->Form->input('parent_id', [
'options' => $parentCategories,
'empty' => 'No parent category'
]);
TreeBehavior帮助您管理数据库表中的分层树结构。 它使用MPTT逻辑来管理数据。 MPTT树结构针对读取进行了优化,这通常使得它们非常适合阅读诸如博客的重型应用程序。
如果打开src / Model / Table / CategoriesTable.php文件,您将看到TreeBehavior已在initialize()
方法中附加到您的CategoriesTable。 Bake将此行为添加到包含lft
和rght
列的任何表:
$this->addBehavior('Tree');
通过附加TreeBehavior,您将能够访问一些功能,如重新排序类别。 我们会看到这一刻。
但是现在,您必须在类别添加和编辑模板文件中删除以下输入:
echo $this->Form->input('lft');
echo $this->Form->input('rght');
rght
列的验证器中禁用或除去requirePresence:
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('lft', 'valid', ['rule' => 'numeric'])
// ->requirePresence('lft', 'create')
->notEmpty('lft');
$validator
->add('rght', 'valid', ['rule' => 'numeric'])
// ->requirePresence('rght', 'create')
->notEmpty('rght');
}
当保存类别时,这些字段由TreeBehavior自动管理。
使用网络浏览器,使用/yoursite/categories/add controller操作添加一些新类别。
在类别索引模板文件中,您可以列出类别并对其重新排序。
让我们修改你的CategoriesController.php中的索引方法,并添加moveUp()
和moveDown()
方法,以便能够重新排序树中的类别:
class CategoriesController extends AppController
{
public function index()
{
$categories = $this->Categories->find()
->order(['lft' => 'ASC']);
$this->set(compact('categories'));
$this->set('_serialize', ['categories']);
}
public function moveUp($id = null)
{
$this->request->allowMethod(['post', 'put']);
$category = $this->Categories->get($id);
if ($this->Categories->moveUp($category)) {
$this->Flash->success('The category has been moved Up.');
} else {
$this->Flash->error('The category could not be moved up. Please, try again.');
}
return $this->redirect($this->referer(['action' => 'index']));
}
public function moveDown($id = null)
{
$this->request->allowMethod(['post', 'put']);
$category = $this->Categories->get($id);
if ($this->Categories->moveDown($category)) {
$this->Flash->success('The category has been moved down.');
} else {
$this->Flash->error('The category could not be moved down. Please, try again.');
}
return $this->redirect($this->referer(['action' => 'index']));
}
}
<div class=>
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li><?= $this->Html->link(__('New Category'), ['action' => 'add']) ?></li>
</ul>
</div>
<div class="categories index large-10 medium-9 columns">
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Id</th>
<th>Parent Id</th>
<th>Lft</th>
<th>Rght</th>
<th>Name</th>
<th>Description</th>
<th>Created</th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($categories as $category): ?>
<tr>
<td><?= $category->id ?></td>
<td><?= $category->parent_id ?></td>
<td><?= $category->lft ?></td>
<td><?= $category->rght ?></td>
<td><?= h($category->name) ?></td>
<td><?= h($category->description) ?></td>
<td><?= h($category->created) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $category->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $category->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $category->id], ['confirm' => __('Are you sure you want to delete # {0}?', $category->id)]) ?>
<?= $this->Form->postLink(__('Move down'), ['action' => 'moveDown', $category->id], ['confirm' => __('Are you sure you want to move down # {0}?', $category->id)]) ?>
<?= $this->Form->postLink(__('Move up'), ['action' => 'moveUp', $category->id], ['confirm' => __('Are you sure you want to move up # {0}?', $category->id)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
在ArticlesController
,我们将得到所有类别的列表。 这将允许我们在创建或编辑文章时为文章选择类别:
// src/Controller/ArticlesController.php
namespace App\Controller;
use Cake\Network\Exception\NotFoundException;
class ArticlesController extends AppController
{
// ...
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->getData());
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your article.'));
}
$this->set('article', $article);
// Just added the categories list to be able to choose
// one category for an article
$categories = $this->Articles->Categories->find('treeList');
$this->set(compact('categories'));
}
}
文章添加文件应该看起来像这样:
<!-- File: src/Template/Articles/add.ctp -->
<h1>Add Article</h1>
<?php
echo $this->Form->create($article);
// just added the categories input
echo $this->Form->input('category_id');
echo $this->Form->input('title');
echo $this->Form->input('body', ['rows' => '3']);
echo $this->Form->button(__('Save Article'));
echo $this->Form->end();