How can I write this sql query in Laravel?
http://sqlfiddle.com/#!9/1249d9/30
select `tableA`.*, `tableB`.`start_date`, `tableB`.`end_date`, `tableB`.`price`
from `tableA`
right join(
SELECT id, start_date, end_date, pro_id, price, DATEDIFF(`tableB`.`end_date`, '2021-03-07') diff
FROM `tableB`
GROUP BY id order by diff asc
) `tableB` on `tableA`.`id` = `tableB`.`pro_id`
where (date(`end_date`) >= '2021-03-07')
group by `tableA`.`id`
order by `price` desc
I tried like this but it gave an error "Call to undefined method October\Rain\Database\QueryBuilder::joinSub()".
What should I do for this? or how should a new query be? Can you give a clue about this?
$diffPrice = \DB::table('tableB')
->select('id', 'end_date', 'pro_id', 'price', \DB::raw('DATEDIFF(`tableB`.`end_date`, 0) diff'))
->where('is_published', true)
->groupBy('user_id')
->orderBy('diff', 'ASC');
$query->joinSub($diffPrice, 'tableB', function ($join) {
$join->on('tableA.id', '=', 'tableB.pro_id');
})
->select('tableA.*', 'tableB.start_date', 'tableB.end_date', 'tableB.price')
->where(function($sq) use ($postFrom) {
$sq->when($postFrom[0]=='0', function ($syq) {
$today = Carbon::now()->format('Y-m-d');
$syq->whereDate('end_date', '>=', $today);
}, function ($stq) use ($postFrom) {
$stq->whereDate('start_date', '<=', $postFrom[0])
->whereDate('end_date', '>=', $postFrom[0]);
});
})->groupBy('tableA.id')->orderBy('price', $sortDirection);