I have a project in which a must get a budget_type estimated value per year based on multiple commands estimated prices.
So I have budget_type table, budgets table and commands table.
Budget_type [id, name]
Budgets [id, type_id, year, month]
Commands[id, budget_id, estimated_value, units]
All table are related.
I’ve set a virtual attribute year for the budget_type model (it gets its value from a POST request) and now I have a function getEstimatedValue in budget_type model in which I have a select query like this:
$model = new BudgetType;
$model ->attributes = $_POST['BudgetType];
//i render my view
When i try to build a grid or export it to excel - with $model->search(); - it gives me that error.
I wonder if i can get estimated value as an attribute because i have much more budget-types and i want to filter them by year. (i want to be able to access them as $model->estimatedValue)
My point was for you to test the code to see that it works…
in my example you can use
$model->estimatedValue;
without a problem…
then you would ask yourself how come this works now… but in my example it does not… and possibly you would understand that $this->year is empty in your case.
With your additional info: the reason why it’s not working for you (I think) is that when the seach() method is called $this->year is empty as it did not get the value from the $_POST array
class BudgetType extends CActiveRecord {
public $year;
public function relations() {
return array(
'budgets' => array(self::HAS_MANY, 'Budget', 'type_id'),
);
}
public function getEstimatedValue() {
//this->year is empty
$sum = Yii::app()->db->createCommand()
->select('SUM(estimated_price * units)')
->from('commands com')
->join('budgets bug', 'com.budget_id = bug.id')
->where('bug.year = ' . $this->year)
->queryAll();
return $sum;
}
public function search(){
$criteria = new CDbCriteria;
$criteria->compare('name', $this->name, true);
// here if I dump $this->year it returns me $_POST['BudgetType']['year'] value
if ($this->year != "") {
$criteria->with = array('budgets');
$criteria->compare('budgets.year', $this->year);
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
//and other built in methods
}
I will try your suggestion to pass year as a parameter to see if it works.