php – 使用AR findAll函数在使用with语句时只返回一个对象
我的Yii安装存在问题,我正在尝试获得一个相当基本的查询,但我没有得到结果,因为在线教程说我应该得到.我有两个看起来像这样的模型:
价钱: class Pricing extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return Pricing the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'pricing'; } /** * @return string the primary key */ public function primaryKey(){ return 'ID'; } ... /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'xpricing_routes' => array(self::HAS_MANY,'PricingRoutes','ID_pricing'),); } 和PricingRoutes: class PricingRoutes extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return PricingRoutes the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'pricing_routes'; } /** * @return string the primary key */ public function primaryKey(){ return 'ID'; } ... /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'xpricing' => array(self::BELONGS_TO,'Pricing',); } 然后在控制器中我们有: $criteria = new CDbCriteria; $criteria->with = array('xpricing_routes'); $criteria->together=true; $pricing_records = Pricing::model()->findAll($criteria); $pricing_records_arr = CHtml::listData($pricing_records,'id','name'); echo '<pre>'; print_r($pricing_records); print_r($pricing_record_arr); echo '</pre>'; 您可能已经知道,我们有2个名为pricing和pricing_routes的表.定价路由表有一个名为ID_pricing的外键,它转到定价表中的ID字段.定价表有一个条目,pricing_routes表有4个条目,它们都具有ID_pricing字段中定价表中一个项目的主键.所以我们应该得到4个结果给我们正在运行的查询,当我运行Yii用AR生成的查询时,这就是我得到的. 我们遇到的问题是$pricing_records变量是一个只有一个Pricing对象的数组.该对象包含我们需要的数据,但不是真正可用的数据. $pricing_records_arr变量只是一个空数组.我找到的文档似乎表明我们应该获得一组定价对象,每个定价对象都包含来自pricing_routes表的信息.我们知道使用AR可能不是获取此数据的最佳方式,但我们有理由让这个工作,所以任何有关如何做到这一点的想法将非常感激. 编辑: 事实证明,这最终误解了我的回归.对这个问题的评论给了我所需要的信息. 解决方法
如果你打电话
$pricing_records = Pricing::model()->findAll($criteria); 您将只获得一个活动记录,其中的属性填充了表“定价”中的值. $pricing_records->xpricing_routes 其中“xpricing_routes”是您在模型中正确定义的关系的名称.它返回PricingRoutes数组,如果没有匹配的记录,则返回null. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |