There are two tables: bill (bill) and detail (bill details)
bill fields: billid (bill ID), billdate (billing date), total (total amount)...
detail fields: detailid (detail ID), billid (bill ID), amount (amount), incometype (income category)...
Build two models:
class Bill extends Model {
//Associated to the bill detail table
public function detail(){
return $this->hasMany('Detail', ' billid');
}
}
class Detail extends Model{
//Associated to the bill table
public function bill(){
return $this->belongsTo('Bill', 'billid');
}
}
Q: If you want to use the model object to calculate the income amount according to the income category in the bill details, how should you write it?
天蓬老师2017-08-21 08:26:43
Obviously, you regard the bill details table as the current model and the bill table as the associated model.
The associated template defaults to an inner join query. It is recommended to divide it into two steps:
First: According to the bill ID, first conduct a related query to obtain all the related data;
Second: Group the obtained data according to income categories, and then perform statistical operations. Pay attention to the usage Alias to distinguish.
It is recommended to use closure query to simplify the operation.
If you don’t understand, you can take a closer look at the official manual about model association query, or look at the relevant parts of the framework source code:
https://www.kancloud.cn/manual/thinkphp5/142358