I'm fairly new working with yii but have plenty of experience with php and sql. I'm hoping that someone more experienced with yii can point me in the right direction. I have two models, Project and Costs, which are related to each other in a many to many relationship through a project_cost table. The reason for this is that costs can be shared between projects. In the project_cost table there is an additional column containing how much of the cost is assigned to the specific project.
So the Project model relations looks like this which is working perfectly fine for getting all the details:
class Project extends CActiveRecord
{
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'projectcost' => array(self::HAS_MANY, 'ProjectCost', 'project_id'),
'cost' => array(self::HAS_MANY, 'Cost', array('cost_id'=>'id'),'through'=>'projectcost'),
//i.e. a many to many relation of cost through the projectcost model
);
}
...
}
In the cost model there is a column named Value and in the project_cost table there is column name Percent. It is easy to construct a function that contains a sql query that gives me the sum for the project cost like this:
select sum(project_cost.Percent*cost.Value)
from project_cost join cost on project_cost.cost_id=cost.id
where project_cost.project_id=1
but is there a way to do the same via relations in yii? I know about STAT relations but am unclear on how they can be applied in this case as most of what I have read so far indicates that relations work best if there are only two models in the relationship.