I've created a subset of my objects to demonstrate the problem I'm having.
Here are my table definitions, not very exciting, but enough to present the problem:
CREATE TABLE HandsetModel (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
label VARCHAR(25) NOT NULL
) ENGINE=InnoDB;
// edit, I left out the foreign key on first post, by mistake
CREATE TABLE Handset (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
label VARCHAR(25) NOT NULL,
handsetModelId INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (handsetModelId) REFERENCES HandsetModel(id) ON DELETE CASCADE
) ENGINE=InnoDB;
Here are my two Models:
class Handset extends CActiveRecord
{
// normal stuff
public function tableName()
{
return 'Handset';
}
public function rules()
{
return array(
array('label','length','max'=>25),
array('label, handsetModelId', 'required'),
array('handsetModelId', 'numerical', 'integerOnly'=>true),
);
}
public function relations()
{
return array(
'handsetModel'=>array(self::HAS_ONE, 'HandsetModel', 'id'),
);
}
}
class HandsetModel extends CActiveRecord
{
// normal stuff
public function tableName()
{
return 'HandsetModel';
}
public function rules()
{
return array(
array('label','length','max'=>25),
array('label', 'required'),
);
}
public function relations()
{
return array(
);
}
}
I created some data by just adding some site controller actions. Here is the code,
public function actionGenerateModels()
{
$handsetModel=new HandsetModel();
$handsetModel->setAttribute('label', 'Treo Pro');
$handsetModel->save();
$handsetModel=new HandsetModel();
$handsetModel->setAttribute('label', 'iPhone');
$handsetModel->save();
}
public function actionGenerateHandsets()
{
$handsetModels=HandsetModel::model()->findAll();
foreach ($handsetModels as $handsetModel)
{
for($i = 0; $i < 3; ++$i)
{
$handset=new Handset();
$handset->setAttribute('label', $handsetModel->label . ' ' . $i);
$handset->setAttribute('handsetModelId', $handsetModel->id);
$handset->save();
}
}
}
Then on my index, I just show the list of Handsets,
public function actionIndex()
{
$handsets=Handset::model()->with('handsetModel')->findAll();
$this->render('index', array('handsets'=>$handsets));
}
And here is my index,
<table border=1 width=500px>
<tr><td align=center>Handset</td><td align=center>Model</td></tr>
<?php foreach($handsets as $handset): ?>
<tr>
<td><?php echo $handset->label; ?></td><td><?php echo $handset->handsetModel->label; ?></td>
</tr>
<?php endforeach; ?>
</table>