gpt4 book ai didi

sql - 从 yii 中的两个相关模型中检索两列的总和

转载 作者:行者123 更新时间:2023-12-04 15:48:51 25 4
gpt4 key购买 nike

我是 yii 的新手,但对 php 和 sql 有丰富的经验。我希望对 yii 更有经验的人能给我指明正确的方向。我有两个模型,Project 和 Costs,它们通过 project_cost 表以多对多的关系相互关联。这样做的原因是成本可以在项目之间分摊。在 project_cost 表中有一个附加列,其中包含分配给特定项目的成本。

所以项目模型关系看起来像这样,它可以很好地获取所有细节:

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

);
}
...
}

在成本模型中有一个名为 Value 的列,在 project_cost 表中有一个名为 Percent 的列。构造一个包含 sql 查询的函数很容易,该查询为我提供了项目成本的总和,如下所示:

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

但是有没有办法通过 yii 中的关系来做同样的事情?我知道 STAT 关系,但不清楚如何在这种情况下应用它们,因为到目前为止我读到的大部分内容都表明,如果关系中只有两个模型,关系效果最好。

最佳答案

您可以创建一个范围来获取此数据,在您的项目模型中创建一个方法,例如:

public function withAdjustedCost()
{
$this->getDbCriteria()->mergeWith(array(
'with'=>array(
'projectcost',
'cost',
),
'select'=>'*, sum(projectcost.Percent*cost.Value) as adjustedCost',
));

return $this;
}

然后您应该能够在抓取项目模型时使用它;

$models = Project::model->withAdjustedCost()->findAll();

我没有测试过它,您可能需要稍微修改一下,或者可能需要将 $adjustedCost 定义为模型的属性才能访问它(话又说回来,也许不是)...无论如何,可能是一个前进的方向。

关于sql - 从 yii 中的两个相关模型中检索两列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13156854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com