问题
atk4.2.1
I have two models Invoice and Payment, I want to add a field (expression) in the invoice, I can calculate the already amount paid (it can have several partial payment), I added a join and an expression, dut they don't work, what is the right way to write that expression?
class Model_Invoice extends Model_Table {
public $table='invoice';
function init(){
parent::init();
$this->hasOne('Customer');
$this->hasOne('Plan');
$this->addField('date')->type('date');
$this->addField('amount')->type('money');
$this->addField('cancelled')->type('boolean')->defaultValue(false);
$this->join('payment','id');
$this->addExpression('amountPaid')->set('sum(payment.amount)')
//*****above expression is not working*********//
}
}
.
class Model_Payment extends Model_Table {
public $table='payment';
function init(){
parent::init();
$this->hasOne('Invoice');
$this->addField('date')->type('date');
$this->addField('concept');
$this->addField('amount')->type('money');
}
}
I might an expression like this instead:
$this->addExpression('amountPaid')->set('(SELECT sum(amount) FROM payment where invoice_id=**CURRENT ID**)');
But how do I get the CURRENT ID in the Model???
回答1:
Got it! It was somehow documented here: http://agiletoolkit.org/learn/understand/model/intro
This is the right way to do it: Inside Model_Invoice:
$this->hasMany('Payment');
$this->addExpression('amountPaid')->set($this->refSQL('Payment')->sum('amount'));
Now I really understood what's the porpuse of hasMany()
来源:https://stackoverflow.com/questions/11572856/how-to-add-a-field-calculated-from-another-model-table-in-agile-toolkit