我有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原则?
答案 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();
同样适用于其他人。