Yii2两列的计算结果差异



我找不到与我认为更容易解决的问题相关的解决方案。我有两列数值​​INT(5(,在第三个中,我应该得到每一行的差的结果。

我从这个链接的加法解决方案中得到了提示,但每行都返回(没有值(。

在型号Sistop.hp:中

public function getDiff()
{
$this->diff = 0;
if (is_numeric($this->qdsistop) && is_numeric($this->qusistop)) {
$this->diff = $this->qdsistop - $this->qusistop;
}
return $this->diff;
}

在SistopSearch.php 中

class SistopSearch extends Sistop
{
public function attributes()
{
return array_merge(parent::attributes(), ['diff']);
}
......
public function search($params)
{
$query = Sistop::find()->select('*, (`qdsistop` - `qusistop`) AS `diff`');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// enable sorting for the related columns
$dataProvider->sort->attributes['diff'] = [
'asc' => ['diff' => SORT_ASC],
'desc' => ['diff' => SORT_DESC],
];

.....
if (is_numeric($this->diff)) {
$query->having([
'diff' => $this->diff,
]);
}

结果是相同的:(没有值(对于每一行。

提前谢谢。

addSelect与数组输入参数一起使用:

$query = Sistop::find();
$query->addSelect(['([[qdsistop]] - [[qusistop]]) AS [[diff]]']);
// more examples:
$query->addSelect(['SUM(amount) AS total_annual', 'IF(val > 0, 1, 0) AS is_selected']);
$query->addSelect(['DATE_FORMAT(date_created,'%Y-%m') AS yymm']);
$query->andWhere("[[diff]] >= :limit", [':limit' => 100]);
$query->addGroupBy(['is_selected', 'yymm']);
$query->orderBy(['diff' => SORT_DESC])

请参阅Yii2指南。

最新更新