如何使用cakephp 2在视图中显示树视图

xienkqul  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(256)

enter image description here嗨,伙计们,我在cakephp 2中显示树视图时遇到了问题...使用相同的表作为父表,使用相同的子表作为关系。

表媒体目录

| 标识符|职务名称|父标识|
| - -|- -|- -|
| 一个|测试1|零值|
| 2个|测试2|零值|
| 三个|测试三|一个|
| 四个|测试四|一个|
| 五个|测试五|三个|
| 六个|测试六|2个|
| 七个|测试七|2个|

内容控制器.php

public function index()
{
    $Treeview = $this->MediaDirectory->find("all", 
        array(
            'conditions' => array(
                'MediaDirectory.parent_id' => null
            )
        )
    );

    $this->set(compact('$Treeview'));
}
ws51t4hk

ws51t4hk1#

First I don't understand how can you have 2 times a field named parent_id in your table. You should remove the one which is null. You need 3 differents fields in your table :

*parent_idto store the id of the parent object.
*lftto store the lft value of the current row.
*rghtto store the rght value of the current row.

Then you need to add the following line in your model :

public $actsAs = array('Tree');

If you want that it to work, you have to insert your data using your controller. lft and rght are automatically defined by the core when you save some data in it.
For instance, in your controller

$data['MediaDirectory']['parent_id'] = 10;
$data['MediaDirectory']['title'] = 'Test 1';
$this->MediaDirectory->save($data);

And after that you should replace your code in your controller like this :

public function index() {
  $Treeview = $this->MediaDirectory->find("threaded", 
    array(
      'conditions' => array(
        'MediaDirectory.parent_id'=> null,
        'MediaDirectory.fk_id'=> $cid // Not sure what this is suppose to do
      )
    )
  );
  $this->set(compact('Treeview')); // TreeviewChild name was wrong
}

The query build**find("threaded")**is suppose to return tree data. Do not hesitate to use debug() function to visualize what data you are currently manipulating.
Everything you need is there about the version 2.x : https://book.cakephp.org/2/en/core-libraries/behaviors/tree.html

相关问题