php - 用laravel eloquent根据城市和支付类型进行求和分组

标签 php mysql laravel eloquent

我有三个不同的表:城市、付款类型和付款。我想创建付款摘要报告。

城市表:

cities table

然后是付款类型表:

payment type

和付款表:

payments

我想要得到的是(我想创建这个摘要)

summary

因此,根据摘要城市不会重复并按 payment_types 分组。

如何使用 Eloquent 创建此查询?

最佳答案

首先,您需要为 Eloquent 模型创建适当的关系,如下所示:

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

}

付款.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 的更多信息,泰勒用例子很好地解释了一切。

关于php - 用laravel eloquent根据城市和支付类型进行求和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473080/

相关文章:

php - Laravel - 选择列值第一次出现的行

php - Laravel Eloquent : Select where related table has x, 但从相关表中排除某些行

php - Nginx + Xamp + SSL 奇怪的行为

php - 如何直接在电子邮件通知上管理答案

javascript - 单选按钮不会从 "optionA"更改 - AJAX/JAVASCRIPT

java - 此查询是否可以使用 Criteria 或 DetachedCriteria Hibernate

php - 删除路径中带点的元素不起作用

php - 在 strpos() 的字符串中使用正则表达式

JavaPreparedStatement和AlterTable语法错误

laravel - Laravel query.php 中的硬编码 id 列