Tables in MySQL:
field:
id pk
field_option
id pk
feild_id int(11)
ALTER TABLE `field_option` ADD CONSTRAINT `option_field` FOREIGN KEY ( `feild_id` ) REFERENCES `agahi_fixed`.`field` (
`id`
) ON DELETE CASCADE ON UPDATE RESTRICT;
Relation Field model:
return array(
'fieldOption' => array(self::HAS_MANY, 'FieldOption', 'feild_id'),
);
Relation FieldOption model:
return array(
'feild' => array(self::BELONGS_TO, 'Field', 'feild_id'),
);
In controller:
if(Field::model()->exists('cat_id = :catId', array(":catId"=>$_POST['catid']))){
$criteria=new CDbCriteria;
//$criteria->select='*';
$criteria->condition='cat_id=:catId';
$criteria->params=array(':catId'=>$_POST['catid']);
$criteria->with = 'fieldOption';
$field=Field::model()->findAll($criteria);
header('Content-type: application /json');
$jsonRows=CJSON::encode($field);
echo $jsonRows;
}
but it does not work with just select records in field table.
Why?
this way you won't achive what your looking for,
when you fetch your records using with
it will fetch associated records, meaning : eager loading
not lazy
, but when you json encode your model, It will get attributes of your main model, not any relations, If you want any related data to get encoded with the model, you have to explicitly say so. I suggest make an empty array :
$result = array();
make a loop over your model and append to this result, from model to related model
foreach($field as $model)
{
$record = $model->attributes; // get main model attributes
foreach($model->fieldOption as $relation)
$record['fieldOption'][] = $relation->attributes; // any related records, must be explicitly declared
$result[] = $record;
}
now you have exactly what you need, then echo it
echo CJSON::encode($result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.