[英]Yii relation — MySQL foreign key
Tables in MySQL: MySQL中的表:
field: 领域:
id pk
field_option 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: 关系FieldOption模型:
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. 当你使用抓取你的记录
with
将取回相关记录,这意味着: eager loading
不lazy
,但是当你的JSON编码模型,它将让您的主模型的属性,没有任何关系,如果你想要的任何相关数据,以获得编码对于模型,您必须明确地说出这一点。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.