【发布时间】:2013-01-29 16:45:06
【问题描述】:
我的 Yii 安装出现问题,我试图返回一个相当基本的查询,但我没有得到在线教程说我应该得到的结果。我有 2 个大致如下的模型:
定价:
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'),
);
}
和定价路线:
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', 'ID_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 个表,分别称为定价和定价路径。定价路由表有一个名为 ID_pricing 的外键,它指向定价表中的 ID 字段。定价表有一个条目,pricing_routes 表有 4 个条目,它们都在 ID_pricing 字段中具有定价表中一项的主键。因此,我们正在运行的查询应该得到 4 个结果,当我运行 Yii 使用 AR 生成的查询时,这就是我得到的结果。
我们遇到的问题是 $pricing_records 变量是一个只有一个定价对象的数组。该对象包含我们需要的数据,但不是真正可用的方式。 $pricing_records_arr 变量只是一个空数组。我发现的文档似乎表明我们应该获取一组定价对象,每个定价对象也包含来自pricing_routes 表的信息。我们知道,使用 AR 可能不是获取这些数据的最佳方式,但我们有理由让它发挥作用,所以任何关于如何做到这一点的想法都将不胜感激。
编辑:
事实证明,这最终导致我对我得到的结果产生了误解。这个问题的 cmets 给了我我需要的信息。
【问题讨论】:
-
尝试不使用
Pricing::model()->with('xpricing_routes')->findAll();等条件 -
感谢您的回复,但我们实际上已经尝试过了,并且得到了相同的结果。
-
那么你必须找出在后台执行的 sql 查询到底是什么。
CProfileLogRoute可以帮到你 -
不不。这不是确切的问题。您必须将行更改为
$pricing_records_arr = CHtml::listData($pricing_records->xpricing_routes, 'id', 'name');才能在数组中获取 4 个值 -
@dInGd0nG 请将您的 cmets 展开/合并为答案
标签: php activerecord yii