我有三个不同的表:城市,payment_types和付款。我想为付款创建摘要报告。
城市表:
然后付款类型表:
付款表:
我想得到的是(我想创建此摘要)
所以,根据汇总城市不重复并按payment_types分组。
如何使用Eloquent创建此查询?
答案 0 :(得分:0)
首先,您需要为您的雄辩模型创建适当的关系,例如:
City.php
class City extends Model {
public function payments() {
return $this->hasMany('App\Payment');
}
}
PaymentType.php
class PaymentType extends Model {
public function payments() {
return $this->hasMany('App\Payment');
}
}
Payment.php
class Payment extends Model {
public function city() {
return $this->belongsTo('App\City');
}
public function payment_type() {
return $this->belongsTo('App\PaymentType');
}
public function scopeFromCity($query, $cityId) {
return $query->where('city_id', $cityId);
}
}
完成初始设置后,您就可以开始创建报告了:
// Get all cities from DB
$cities = \App\City::all();
// Loop through each city
$cities->each(function($city) {
// Print city id and name
echo "City ID {$city->id}\n";
echo "City Name {$city->name}\n";
// Now we will fetch all unique payment types for this city
// and we will loop through each of them
// calculating the total of payments done
// for this payment type and city_id
$paymentTypes = \App\PaymentType::whereIn('id', \App\Payment::where('city_id', $city->id)->lists('payment_type_id'));
$paymentTypes->distinct()->get()->each(
function($paymentType) use ($city) {
echo "Payment type {$paymentType->type}\n";
$total = $paymentType->payments()->fromCity($city->id)->sum('payment');
echo "Total {$total}\n";
});
});
您可以从documentation找到有关Eloquent的更多信息,Taylor已经通过示例很好地解释了所有内容。