Imagine:
I have a adverts table with a price column. I have a pricerange table with a price_from and a price_to column.
I want to setup my Eloquent models, so that I can fetch the matching adverts from a Pricerange instance. Or query the pricerange table, and do a count on all matching adverts. Optionally, get the query from the adverts-relation and add more criteria.
In other words, I'd like the equivalent of this raw query:
SELECT priceranges.*, (
SELECT COUNT(adverts.id) FROM adverts
WHERE adverts.price >= priceranges.price_from
AND adverts.price < priceranges.price_to
) AS adverts_count
FROM priceranges
or
SELECT priceranges.*, COUNT(adverts.id) AS adverts_count
FROM priceranges
INNER JOIN adverts ON adverts.price >= priceranges.price_from
AND adverts.price < priceranges.price_to
GROUP BY priceranges.id
Is this possible? I searched on custom relations, but I cannot find a working solution.
Thanks in advance!
You can do something like this,
Priceranges::join('adverts',function($join){
$join->on('adverts.price','>=','priceranges.price_from')->orOn('adverts.price','<','priceranges.price_to');
})
->groupBy('priceranges.id')
->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.