In my example I have Flight and Airport models. Airport has many Flights and Flight belongs to Airport.
Airport has an integer attribute called daysAfterFlightLanded, which I use to know how many days after a Flight landed I want to show it in results. Flight has datetime attribute called landed_at.
I need to retrieve all Flights (preferably with query builder) that has not landed yet and those which has landed but summing daysAfterFlightLanded is greater than today.
I do not know how to implement this sum at the query.
Hope I'm being clear.
Thanks in advance.
Will give you a date 5 days into the future, formatted as a datetime string just as it appears in your database. Then you can use something like query scopes (http://laravel.com/docs/5.1/eloquent#query-scopes) to make your query reusable and readable.
What I am trying to do is retrieve records (with Eloquent or query builder) filtering by (date attribute + days attribute from related record) > Carbon::now().
@GastonUy Oh I see now… sorry, I misread it. You'll most likely have to work with a stored function for that (http://www.mysqltutorial.org/mysql-stored-function/). From by brief experiences with them, they're not extremely pleasant to work with, but your example seems simple enough that it shouldn't be too much of a hassle.
Alternatively, you could do an optimistic selection where you select the flights that could be relevant, and then filter the results through the handy collection methods.
You'll end up with something like this:
$flights = Flight::where('has_landed', '=', 1)->get(); // You'll want to add a date range or something to lower the returned results
$flights->filter(function ($flight) {
return $flight->daysAfterFlightLanded + $flight->landed_on > now;
});