Hello,
I am working on result display page and have problem with filters.
Problem1
I want to display all possible makes and models + display how many results we have.
Question1
How can I avoid duplicating query? In my understanding I am not able to use the same result query to get possible makes and models because it have pagination and it shows me results only for this page (10 results)
Problem2 (solved)
Close to every single record I want to display 1 photo if it have. I created method thumb() in ad model. but I am getting there N+1 problem
select * from `photos` where `photos`.`ad_id` = '30' and `photos`.`ad_id` is not null and `type_id` = '2' limit 1
340μs
project35.dev
select * from `photos` where `photos`.`ad_id` = '36' and `photos`.`ad_id` is not null and `type_id` = '2' limit 1
340μs
project35.dev
select * from `photos` where `photos`.`ad_id` = '40' and `photos`.`ad_id` is not null and `type_id` = '2' limit 1
320μs
project35.dev
Question2
How you solving this issue? how to get 1 image if it is available?
Models:
//Ad model
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
public function car()
{
return $this->hasOne(Car::class);
}
public function bike()
{
return $this->hasOne(Bike::class);
}
public function photos()
{
return $this->hasMany(Photo::class);
}
public function thumb()
{
if (count($this->photos)) {
return $this->photos()->where('type_id', 2)->first()->link;
}
return 'images/no-image.jpg';
}
// Car model
public function ad()
{
return $this->belongsTo(Ad::class);
}
public function make()
{
return $this->belongsTo(Make::class);
}
public function model()
{
return $this->belongsTo(Vmodel::class);
}
Controller:
$vehicles = new Ad;
$vehicles = $vehicles
->with('car','car.make','car.model','photos')
->join('cars','cars.ad_id','=','ads.id')
->where('status', 1)
->where('blocked', 0)
->where('confirmed', 1)
->where('paid', 1)
->whereHas('car');
if (request()->has('make')) {
$vehicles = $vehicles->whereHas('car',function($q) {
$q->where('make_id',request('make'));
});
}
if (request()->has('model')) {
$vehicles = $vehicles->whereHas('car',function($q) {
$q->where('model_id',request('model'));
});
}
if (request()->has('sort')) {
$vehicles = $vehicles->orderBy('ads.created_at',request('sort'));
}
if (request()->has('paginate')) {
$vehicles = $vehicles->paginate(request('paginate'));
}else {
$vehicles = $vehicles->paginate(10);
}
$vehicles = $vehicles->appends([
'sort' => request('sort'),
'paginate' => request('paginate')
]);
Thank you for help!