I have the following models and relations: Ads has many-to-many with Cities Ads has many-to-many with Categories
Now I want to get Ads for a specific City and specific Category. So in SQL I do the following and getting the correct result:
select * from ads
inner join ad_cities on ad_cities.adId = ads.id
inner join ad_categories on ad_categories.adId = ads.id
where ad_cities.cityId = 1525
and ad_categories.categoryId = 6
I know it can be done using DB:table(xxxx)->join->.... But I want to know if the same can be done on the model without taking the DB:table approach.
I tried the following and getting the result, but the query generated doesn't seem to be efficient.
return Category::find(6)
->ads()
->whereHas('cities', function ($query) {
$query->where('cityId', '=', '1525');
})
->where('statusName', '=', 'PUBLISHED')
->orderBy('publishedAt', 'DESC')
->simplePaginate($pageSize);
This generated the following query:
select `ads`.*, `ad_categories`.`categoryId` as `pivot_categoryId`, `ad_categories`.`adId` as `pivot_adId` from `ads` inner join `ad_categories` on `ads`.`id` = `ad_categories`.`adId` where `ad_categories`.`categoryId` = '6' and (select count(*) from `cities` inner join `ad_cities` on `cities`.`id` = `ad_cities`.`cityId` where `ad_cities`.`adId` = `ads`.`id` and `cityId` = '1525') >= 1 and `statusName` = 'PUBLISHED' order by `publishedAt` desc limit 16 offset 0
Appreciate your help. Thanks, Velu
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire