Complicated eloquent queries

243 0 0 0

Last Updated : 2021-12-03 00:28:13

Here is a sample of a complicated query that includes where and with and inner queries. This snuppet is the one used to get the legislative event stream on the dashboard in the GovIQ project.

$memberId = Auth::user()->id ;
$allResultsArray = [];
$months = 36 ; //Please set this to 2 months when the feeds works perfectly, Now three years.
$dateLimit = time() - $months*31*24*60*60 ; //Two Months Earlier
$dateLimit = date("Y-m-d 00:00:00",$dateLimit) ;

$qqAllNewProvincial = ProvincialBillModel::with([
'events'=>function($eventQ2) use ($dateLimit){
###$eventQ2->where('date', '>=', "$dateLimit")->groupby('bill_id')->orderBy('date','desc');
//$eventQ2->where('date', '>=', "$dateLimit")->orderBy('date','desc')->first();
$eventQ2->where('date', '>=', "$dateLimit")->orderBy('date','desc');
}
])->whereHas(
'events',function($eventQ) use ($dateLimit){
$eventQ->where('date', '>=', "$dateLimit");
})->whereHas(
'favorites',function($favoriteQ) use ($memberId){
$favoriteQ->where('user_id',$memberId);
}
)->get();



$qqAllNewFederal = FederalBillModel::with([
'events'=>function($eventQ2) use ($dateLimit){
###$eventQ2->where('date', '>=', "$dateLimit")->groupby('bill_id')->orderBy('date','desc');
//$eventQ2->where('date', '>=', "$dateLimit")->groupby('bill_id')->orderBy('date','desc');
$eventQ2->where('date', '>=', "$dateLimit")->orderBy('date','desc');

//$eventQ2->where('date', $eventQ2->max('date'))->where('date', '>=', "$dateLimit")->groupby('bill_id');
###$eventQ2->where('date', '>=', "$dateLimit")->orderBy('date','desc')->first();
}
])->whereHas(
'events',function($eventQ) use ($dateLimit){
$eventQ->where('date', '>=', "$dateLimit");
})->whereHas(
'favorites',function($favoriteQ) use ($memberId){
$favoriteQ->where('user_id',$memberId);
}
)->get();

$finalMergedResults = $qqAllNewFederal->merge($qqAllNewProvincial);

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .