怎么用表与自己联系?

aya*_*aya 3 cakephp associations

怎么用表与自己联系?我用cakephp和table是Section:

create table SECTIONS
(
   SECTIONID            int(11) not null auto_increment,
   TITLE                char not null,
   CONTROLID            int(11) not null,
   SECTIONPARENTID      int(11),
   primary key (SECTIONID)
)
Run Code Online (Sandbox Code Playgroud)

这个表与自己有关联,我使用属于并且有很多关联,我的模型是:

class Section extends AppModel {
    var $name = 'Section';
    var $primaryKey = 'SECTIONID';
    var $displayField = 'TITLE';
}
Run Code Online (Sandbox Code Playgroud)

我使用属于并且在两个表中有许多关联.但我不能在这个例子中使用.感谢帮助.

Ric*_*ome 6

一旦你知道了这个技巧,自我参照模型在Cake中很简单,但是你不会因为不使用Cake命名约定而给自己带来任何好处.我假设您使用的是不受控制的数据源:-)

Class Section extends AppModel {

  var $belongsTo = array(
    'Parent'=>array(
      'className'=>'Section',
      'foreignKey'=>'SECTIONPARENTID'
    )
  );

  var $hasMany = array(
    'Children'=>array(
      'className'=>'Section',
      'foreignKey'=>'SECTIONPARENTID'
    )
  );

}
Run Code Online (Sandbox Code Playgroud)

当您运行查询,例如$ this-> Section-> find('first')时,您将获得一个如下所示的返回数组:

section => array(
  SECTIONID,
  ...
  'Parent'=>array(
    'SECTIONID',
    ....
  ),
  'Children'=>array(
    [0] => array(
      [SECTIONID]
    ),
    [1] => array(
      [SECTIONID]
    ),
    ...
  )
)
Run Code Online (Sandbox Code Playgroud)