php - Getting error while counting the relational data in Laravel Eloquent
I'm getting an error while counting the 'with' data in laravel Eloquent Query.
What output I need is to count the number of data related to promotiondetails and use the where condition if it is greater than 0.
$category = $request->input('category');
$sqlDistance = DB::raw('(6371 * acos(cos(radians('.$request->latitude.'))
* cos(radians(latitude))
* cos(radians(longitude)
- radians('.$request->longitude.') )
+ sin(radians('.$request->latitude.') )
* sin(radians(latitude))))');
$offers = Promotion::with(['promotiondetails' => function($q) use($category) {
$q->where('premium', '=', 0);
if($category != 'all'){
$q->where('category', '=', $category);
}
$q->whereRaw('STR_TO_DATE(expiry_date, "%d/%m/%Y") >= CURDATE()');
$q->where('status', '=', 1);
}])
->select('*')
->addSelect(DB::raw("round({$sqlDistance}, 2) AS distance"))
->having("distance", "<", $request->radius)
->where('type', 2)
->where('status', 1)
->where(function ($query){
$query->where('count(promotiondetails)', '>', 0);
})
->orderBy('distance')
->paginate(($request->input('page') == 'all' ? 0 : 10));
Can Someone help me on this?
Error:
Column not found: 1054 Unknown column 'count(promotiondetails)' in 'where clause'
Answer
Solution:
You can use Has or whereHas function to query about a relation's existence. You can find more details here in laravel docs.
$category = $request->input('category');
$sqlDistance = DB::raw('(6371 * acos(cos(radians('.$request->latitude.'))
* cos(radians(latitude))
* cos(radians(longitude)
- radians('.$request->longitude.') )
+ sin(radians('.$request->latitude.') )
* sin(radians(latitude))))');
$offers = Promotion::with(['promotiondetails' => function($q) use($category) {
$q->where('premium', '=', 0);
if($category != 'all'){
$q->where('category', '=', $category);
}
$q->whereRaw('STR_TO_DATE(expiry_date, "%d/%m/%Y") >= CURDATE()');
$q->where('status', '=', 1);
}])
->select('*')
->addSelect(DB::raw("round({$sqlDistance}, 2) AS distance"))
->having("distance", "<", $request->radius)
->where('type', 2)
->where('status', 1)
->has('promotiondetails')
->orderBy('distance')
->paginate(($request->input('page') == 'all' ? 0 : 10));
Source