cakePHP 2.0 find('threaded')问题

Ash*_*elf 2 php cakephp

我在我的Jobs控制器中运行以下命令.

$this->set('jobs', $this->Job->find('threaded', array('conditions' => array('Job.id' => 20))));
Run Code Online (Sandbox Code Playgroud)

现在在我看来我$jobsforeach循环中显示很好,但我的问题是我有使用字段parent_id链接到Job.id的子项.我知道链接工作正常,因为我可以看到数组中的子节点.

    Array
(
[0] => Array
    (
        [Job] => Array
            (
                [id] => 20
                [parent_id] => 0
                [rght] => 2
                [lft] => 1
                [client_id] => tasd
                [contact] => asdf
                [email] => sdf
                [address] => 
                [lat] => 
                [long] => 
                [user_id] => 1
                [request_type_id] => Electrical
                [date_start] => 0000-00-00 00:00:00
                [date_end] => 0000-00-00 00:00:00
                [date_complete] => 0000-00-00 00:00:00
                [date_closed] => 0000-00-00 00:00:00
                [status] => completed
                [brief_desc] => aasdf
                [desc] => asdfasdf
                [cost_est] => 3434.00
                [cost_actual] => 
                [created] => 2011-12-18 20:39:24
                    [modified] => 2011-12-18 20:39:24
            )


        [Children] => Array
            (
                [0] => Array
                    (
                        [id] => 21
                        [parent_id] => 20
Run Code Online (Sandbox Code Playgroud)

我想在父作业下显示子作业.究竟嵌套注释应该如何工作.任何帮助都会很棒.

小智 6

查看find('threaded')正在生成的SQL .您要求所有ID为20的作业(而不是作为Job 20的子作业的所有作业)

由于你有一个lft和rght字段,我假设你附加了Tree行为.这意味着你可以使用children().

$this->Job->id = 20;
$this->Job->children();
Run Code Online (Sandbox Code Playgroud)

但是,这将为您提供一个平面数组,而不是嵌套数组.如果需要嵌套数组,请使用find('threaded')调用中的lft和rght列.

$parentJob = $this->Job->find('first', array(
    'conditions' => array(
        'Job.id' => 20
    )
);

$children = $this->Job->find('first', array(
    'conditions' => array(
        'Job.lft BETWEEN ? AND ?' => array($parentJob['Job']['lft'], $parentJob['Job'])['rght']
    )
);
Run Code Online (Sandbox Code Playgroud)

当然你可以把它归结为一个查询,但我会把它作为一个练习给读者留下(我应该是一本教科书作者)