Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use table that association with itself?

how use table that association with itself ? i use cakephp and table is 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)
)

this table have association with itself and i use belong to and has many association and my model is :

class Section extends AppModel {
    var $name = 'Section';
    var $primaryKey = 'SECTIONID';
    var $displayField = 'TITLE';
}

i use belong to and has many association in two table. but i can't use in this example. thanks for help.

like image 229
aya Avatar asked Nov 26 '25 13:11

aya


1 Answers

Self referential models are simple in Cake once you know the trick, but you aren't doing yourself any favours by not using Cake naming conventions. I'll assume you're using a datasource that's out of your control :-)

Class Section extends AppModel {

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

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

}

When you run a query such as $this->Section->find('first') you'll get a returned array that looks like this:

section => array(
  SECTIONID,
  ...
  'Parent'=>array(
    'SECTIONID',
    ....
  ),
  'Children'=>array(
    [0] => array(
      [SECTIONID]
    ),
    [1] => array(
      [SECTIONID]
    ),
    ...
  )
)
like image 192
RichardAtHome Avatar answered Nov 29 '25 08:11

RichardAtHome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!