0

I have two models with a very simple hasMany relationship:

// Location.php
public function forecasts()
{
    return $this->hasMany('App\Forecast');
}

// Forecast.php

public function location()
{
    return $this->belongsTo('App\Location');
}

Following the Laravel documentation on constraining eager loads, I want to get all Locations along with the latest Forecast belonging to that location, but I can't use the limit() method:

// LocationsApiController.php

public function index()
{
    $locations = Location::with(['forecasts' => function ($query) {
        $query->latest()->limit(1); // LIMIT NOT ALLOWED
    }])->get();

    return response($locations->jsonSerialize(), Response::HTTP_OK);
}

How do I build a query to get latest forecast for each location?

EDIT: It's possible to define a separate hasOne Eloquent relation between Location and Forecast (e.g. latestForecast) and doing the limit there. (That Staudenmeir package looks very interesting too!) However, this relationship would produce a "nonstandard" output in the JSON (ideally the JSON returned would be exactly the same structure as Location::with('forecasts')->get();, just with only one object in the forecasts array instead of multiple). This allows the Vue components on the frontend to be highly reusable and not worry about what context they are being used in, they just render the data.

Erich
  • 2,408
  • 18
  • 40
  • [this question](https://stackoverflow.com/q/2111384/4468423) is asking much the same thing, but in regular sql. will see if i can convert any of the answers to the query builder syntax. – Erich Aug 08 '19 at 00:51
  • 1
    Possible duplicate of [How to find only last row from second table, along with its first table row](https://stackoverflow.com/questions/55145389/how-to-find-only-last-row-from-second-table-along-with-its-first-table-row) – Jonas Staudenmeir Aug 08 '19 at 01:55
  • @JonasStaudenmeir beautiful package you have there! why is that not part of laravel core yet? :) but i still need to overcome the differences in the returned objects. beginning to think that mangling the object after the fact might be the quickest way to go. – Erich Aug 08 '19 at 02:38
  • https://github.com/laravel/framework/pull/26035 – Jonas Staudenmeir Aug 08 '19 at 02:40
  • 1
    Regarding the JSON structure: You can also apply the limit to a `HasMany` relationship. – Jonas Staudenmeir Aug 08 '19 at 02:40
  • my man! much easier than mangling the json after the fact. – Erich Aug 08 '19 at 02:58

0 Answers0