Reputation: 1613
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.
Upvotes: 3
Views: 2529
Reputation: 4313
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]
),
...
)
)
Upvotes: 6