Answer the question
In order to leave comments, you need to log in
How to round up to the lower threshold or to the upper threshold in a request for a tariff, if there is no lower threshold?
Good afternoon.
There is such a structure:
services
-------------
id
prices
-------------
service_id
days
price
In the final order table, I need to generate a price according to this principle. For example, for one service in the prices
table there are records: id | service_id | days | price
--------------------------------------------------
1 | 1 | 3 | 100
2 | 1 | 5 | 200
3 | 1 | 10 | 300
I need this option to be selected if there is a lower threshold value, or if the current one corresponds, for example:
Select 4 days, get - record with id=1
Select 5 days, get - record with id=2
Select 22 days, get - record with id=3
If there is no lower threshold value, then we pull it out with a minimum number of days, for example:
Select 1-2 days, we get - a record with id=1
Otherwise exception / null / 0
Tell me - how to make such a request through a request or Eloquent? Is it possible to do this in 1-2 steps?
Answer the question
In order to leave comments, you need to log in
So far I've done this, but I don't like it:
$prices_min = $this->prices()->limit(1)->orderBy('days')->first();
if($days < $prices_min) {
return $prices_min;
}
$exact_match = $this->prices()->where('days','=',$days)->first();
if($exact_match) {
return $exact_match;
}
$smaller = $this->prices()->where('days','<',$days)->first();
if($smaller) {
return $smaller;
}
throw new NotFoundException('Not Found');
$prices_min = $this->prices()->limit(1)->orderBy('days')->first();
if($days < $prices_min) {
$price = $prices_min;
}
$exact_match = $this->prices()->where('days','=',$days)->orWhere('days','<',$days)->orderByDesc('days')->first();
if($exact_match) {
$price = $exact_match;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question