How to do math operations with model fields or exp

2019-06-14 13:07发布

问题:

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

回答1:

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'));
});


回答2:

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

then you can:

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