Cakephp在没有"儿童"

时间:2015-05-06 13:16:56

标签: cakephp cakephp-2.0

我正在设置一个API而宁愿只在我的数组中使用对象而不是" Modelname" &安培; "儿童"反复洒遍。有没有办法做到这一点?我想一个循环可以解决问题,但我无法弄明白。

      $results = $this->Test->find('threaded', array(
    'fields' => array('id', 'parent_id', 'name'),
      'order' => array('lft ASC') // or array('id ASC')
      ));

  for ($i = 0; $i <= $this->Test->childCount(1); $i++) {
  debug($results[$i]['children']);

  }

  $this->set(array(
    'results' => $results,
    '_serialize' => 'results'
    ));

1 个答案:

答案 0 :(得分:1)

您提供的代码似乎对3.x和2.x都不是唯一的,所以我会为每个代码共享解决方案。

<强> 3.x的

你可以通过传递“孩子们”来获得树节点所有后代的平面列表。作为您的查询中的查找器类型:

$result = $this->Test->find('children', array(
    'for' => $record_id,   // Notice you have to specify 'for' key!
    'fields' => array('id', 'parent_id', 'name'),
    'order' => array('lft ASC')
));

如果您只想查找自己节点的直接子节点,请将“直接”字符传递给“直接”。选项数组中的键:

$result = $this->Test->find('children', array(
    'for' => $record_id,   // Notice you have to specify 'for' key!
    'fields' => array('id', 'parent_id', 'name'),
    'order' => array('lft ASC'),
    'direct' => true
));

更多信息:

3.x Cookbook for TreeBehavior

3.x findChildren() defined in API

3.x API Info for findChildren()

<强> 2.x的

要获得2.x中所有后代的平面列表,请使用TreeBehavior类提供的 - &gt; children()函数:

$result = $this->Test->children(
    $record_id,                   // ID of record to find children for 
    false,                        // Direct = false 
    ['id', 'parent_id', 'name'],  // Fields to include in query
    'lft ASC'                     // Order
)

相反,要仅查找直接后代,您可以将第二个参数传递为true:

$result = $this->Test->children(
    $record_id,                   // ID of record to find children for 
    true,                         // Direct = true 
    ['id', 'parent_id', 'name'],  // Fields to include in query
    'lft ASC'                     // Order
)

更多信息:

2.x Cookbook for TreeBehavior

2.x children() defined in API

2.x API Info for children()

使用Tree数据,CakePHP TreeBehavior可以很好地抽象出许多痛苦。我希望这些信息有所帮助!