Laravel 5.2:如何在同样的权利中加入DRY

时间:2016-11-07 10:55:14

标签: laravel

我有4个正确的联接,区别在于harga_sewa.description

public function method_controller(Request $request, $id){
$dasar = Vehicle::rightJoin('harga_sewa', function ($join){
        $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
    })
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'dasar')
    ->where('vehicles.id', $id)
    ->first();

    $luar_kota = Vehicle::rightJoin('harga_sewa', function ($join){
        $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
    })
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'luar kota')
    ->where('vehicles.id', $id)
    ->first();

    $overtime = Vehicle::rightJoin('harga_sewa', function ($join) {
        $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
    })
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'overtime')
    ->where('vehicles.id', $id)
    ->first();

    $sopir = Vehicle::rightJoin('harga_sewa', function ($join) {
        $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
    })
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'sopir')
    ->where('vehicles.id', $id)
    ->first();

    //get the value of each right join
    $dasar = $dasar->value;
    $luar_kota = $luar_kota->value;
    $overtime = $overtime->value;
    $sopir = $sopir->value;
}

我认为这是丑陋的代码,应该如何遵循DRY原则?

1 个答案:

答案 0 :(得分:0)

Vehicle

中添加范围
public function scopeHargaSewa($query)
    {
        return $query->rightJoin('harga_sewa', function ($join) {
            $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
            $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        });
    }

然后转换此

$dasar = Vehicle::rightJoin('harga_sewa', function ($join){
        $join->on('vehicles.car_class_id', '=', 'harga_sewa.car_class_id');
        $join->on('vehicles.zone_id', '=', 'harga_sewa.zone_id');
    })
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'dasar')
    ->where('vehicles.id', $id)
    ->first();

$dasar = Vehicle::hargaSewa()
    ->select('vehicles.license_plate', 'harga_sewa.value')
    ->where('harga_sewa.description', 'dasar')
    ->where('vehicles.id', $id)
    ->first();

同样适用于其他人。