Cakephp中的协会:BelongsTo无效

时间:2013-07-03 12:20:31

标签: cakephp associations

我对CakePHP中的关联有问题。

我希望Type有很多Sections,所以Section属于Type

模型

   class Type extends AppModel {
        public $name = 'Type';

        public $hasMany = array(
            'Section' => array(
                'className'     => 'Section',
                'foreignKey'    => 'type_id'
            )
        );
    }

class Section extends AppModel {
    public $name = 'Section';
    public $belongsTo = array(
        'Type' => array(
            'className'    => 'Type',
            'foreignKey'   => 'type_id'
        )
    );
}

控制器

class SectionsController extends AppController {

    public function lista() {
            $this->set('sections', $this->Section->find('all'));
    }

}

但结果如下:

array(
    (int) 0 => array(
        'Section' => array(
            'id' => '1',
            'type_id' => '1',
            'name' => 'Advertising',
            'visible' => true
        )
    ),

1 个答案:

答案 0 :(得分:0)

你应该使用

 $this->set('sections', $this->Section->find('all'));

NB:没有Type

这将包括表单中的Type字段。

array(1) {
  [0]=>
  array(2) {
    ["Section"]=>
    array(1) {
      ["id"]=>
      string(1) "1"
    }
    ["Type"]=>
    array(0) {
      ["id"]=>
      string(1) "1"
    }
  }
}

如果关系为Section hasMany Type

,您的代码将有效
相关问题