How to do math operations with model fields or exp

2019-06-14 13:05发布

atk4.2.1

I have this model:

class Model_Cargo extends Model_Table {
public $table='cargo';
function init(){
    parent::init();

    $this->hasOne('Alumno');
    $this->hasOne('Plan');

    $this->addField('fecha')->type('date');
    $this->addField('fechaCreacion')->type('date');
    $this->addField('fechaVencimiento')->type('date');
    $this->addField('name');
    $this->addField('monto')->type('money');
    $this->addField('cancelado')->type('boolean')->defaultValue(false);

    $this->hasMany('Abono');
    $this->addExpression('abonos')->set($this->refSQL('Abono')->sum('monto'));
   }
}

I wanto to make a math operation + or - with two fields: I actually want to substracr field 'monto' with expression 'abonos' how do I do it?

lets say something like this:

$this->addExpression('balance')->set('monto'-'abonos');
//this does not work

I also wold like to addCondition where those fields are equal... can I do that?

something lke:

$this->addCondition('monto','abonos');
//this does not work

2条回答
疯言疯语
2楼-- · 2019-06-14 13:42

I have created an example illustrating how to use calculated fields in expressions:

http://agiletoolkit.org/codepad/model/def

For your problem, you would need something like this:

$this->addExpression('balance')->set(function($m,$q){
    return $q->expr('[f1] - [f2]')
        ->setCustom('f1',$m->getElement('monto'))
        ->setCustom('f2',$m->getElement('abonos'));
});
查看更多
何必那么认真
3楼-- · 2019-06-14 13:50

$this->addExpression("balance")->set("monto - abonos"); and that's it - sql expression.

then you can:

$this->addCondition("balance", ">", 0); or whatever you need.

查看更多
登录 后发表回答