好吧,我找到了this,但是我看不出与我的错误的关系..我是新手 - 我知道这个借口是不可接受的但我试着在我问之前先找到解决方案这里。我希望你能帮助我。
所以我有这段代码,我把这段代码放在视图中:
foreach ($budget as $budget):
if (array_key_exists('year', $_GET)) {
$criteria = new CDbCriteria;
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
$yearBudget = YearlyBudget::model()->find($criteria);
} else {
$yearBudget = new YearlyBudget;
}
endforeach;
然后在那段代码之后,我简单地回应一下:
echo $yearBudget->budget;
然后我得到了非对象错误。我只是不明白并坚持这段代码。请帮忙,谢谢。
的print_r($ yearBudget); :
YearlyBudget Object(
[_new:CActiveRecord:private] =>
[_attributes:CActiveRecord:private] => Array
(
[id] => 1
[mapping_id] => 1
[year] => 2012
[budget] => 2000000
[balance] => 2000000
[created] => 2013-11-20 10:16:29
[updated] =>
)
[_related:CActiveRecord:private] => Array
(
)
[_c:CActiveRecord:private] =>
[_pk:CActiveRecord:private] => 1
[_alias:CActiveRecord:private] => t
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
啊,对不起,如果我的英语不好......
答案 0 :(得分:1)
在访问对象的属性之前,请检查对象是否为空。
if($yearBudget){
echo $yearBudget->budget;
}else{
echo "No Yearly Budget with given criteria";
}
如果您没有得到理想的结果,请仔细检查条件
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
答案 1 :(得分:1)
我强烈建议使用CHtml::value()
方法http://www.yiiframework.com/doc/api/1.1/CHtml#value-detail
echo CHtml::value($yearBudget, 'budget');
当涉及多个相关对象时,这非常方便,并且您不需要检查每个相关模型的存在以访问其属性
echo CHtml::value($budget, 'company.fiscalYear.creator.id');
答案 2 :(得分:0)
在尝试使用您的条件查找后,您需要确保您拥有有效的模型:
foreach ($budget as $budget):
if (array_key_exists('year', $_GET)) {
$criteria = new CDbCriteria;
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
if(YearlyBudget::model()->exists($criteria)) // check if this exists
$yearBudget = YearlyBudget::model()->find($criteria);
else
$yearBudget = new YearlyBudget; // or throw an exception or something
} else {
$yearBudget = new YearlyBudget;
}
endforeach;