CrazyCat
(Crazycat)
October 16, 2013, 3:19pm
1
Hello there,
I’ve a small trouble with a self related table.
The (simplified) structure of the table is:
id int(11) PK
name varchar(50)
parentId int(11)
In my model, I’ve:
public function relations()
{
return array(
'isChildOf' => array(self::BELONGS_TO, 'MyTable', 'id'),
'isParentOf' => array(self::HAS_MANY, 'MyTable', 'parentId'),
);
}
In my admin view, I want to display the parent name:
<?php $this->widget('CGridView', array(
'id'=>'mytable-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
'id',
'name',
array(
'name' => 'parentId',
'value' => '$data->parentId'
),
array(
'header' => 'litteral',
'value' => '$data->isChildOf->name'
),
)); ?>
When displaying my admin, ‘parentId’ is ok, but ‘litteral’ displays the name of the current element, not his father name…
I think I make something wrong, but what ?
Both BELONGS_TO and HAS_MANY uses the same column as fk. Just change id to parentId in isChildOf.
CrazyCat
(Crazycat)
October 16, 2013, 7:32pm
3
Ok, I’ll try tomorrow, I think I’ve tested but I’ve done a lot of combinations and peharps I miss the good one
rootbear
(Alex Xm)
October 17, 2013, 2:02am
4
try this, using ‘parent’ and ‘children’ for relation is much straight-forwards than ‘isChildOf’ and ‘isParentOf’
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'MyTable', 'parentId'),
'children' => array(self::HAS_MANY, 'MyTable', 'parentId'),
);
}
CrazyCat
(Crazycat)
October 17, 2013, 6:47am
5
Hello there, and thanks for your help.
The trouble in the code I gave you was the fk, and before posting I’d tried with the same reference, I gave up because I had errors (trying to get properties of a non-object).
And then, THE solution: the error was in the template, some items haven’t any parent, then I’ve to do:
array(
'header' => 'litteral',
'value' => '($data->parentId!=0)?$data->isChildOf->name:""'
),
Just a stupid error, sorry for the time you spent
Regards
rootbear
(Alex Xm)
October 17, 2013, 8:46pm
6
not sure if this is the right way to do it.
array(
'header' => 'litteral',
'value' => '$data->isChildOf->name'
),
since ‘children’ is supposed to be in has-many relationship while you are trying to display ‘one’
i rather do this:
$children = $model->isChildOf;
if ($children){
//children list here
}
CrazyCat
(Crazycat)
October 18, 2013, 7:33am
7
rootbear:
not sure if this is the right way to do it.
array(
'header' => 'litteral',
'value' => '$data->isChildOf->name'
),
since ‘children’ is supposed to be in has-many relationship while you are trying to display ‘one’
i rather do this:
$children = $model->isChildOf;
if ($children){
//children list here
}
No no
"isChildOf" is well nommed, it contains the id of the parent, or 0, so a record can only be child of one other record.
But I made a small mistake, it’s HAS_ONE and not HAS_MANY in the relation.
I think I’ve peharps an inversion between HAS and BELONG, I’ll verify that.