Search code examples
phplaraveleloquentrelationships

constraining eager loads in laravel 5.1


I need to know how I can make this constrain work.

$senderscore = Server::with(['scores' => function($query){
    $query->orderBy('ts', 'desc')->take(1);
}])->get();

When I use take(1) it gives me an empty score array. I just only need the latest (newest) score. Since I couldn't make this work I'm using it without the take(1) and I just take the first child in the array when I'm looping through the servers in blade. This works fine I just don't like the fact that I'm now loading and passing through 8100 results instead of 9 (1 for each server)

Using only take(1) it will give me just 1 score but it wont be sorted to newest first. I don't get why I can't chain it?

The score and server have a one to many relationship. One score belongs to one server. One server has many scores


Solution

  • Okay, I almost finished my project so I decided to take another look at this and saw the problem almost instantly. The code above does work, just not as I expected it to work. You can most definitely chain.

    I expected there to be 1 score for each server. But it only takes 1 score for the entire query (of course DOH).

    For this to work the way I want I set the limit to the server count.

    $senderscore = Server::with(['scores' => function($query){
        $query->orderBy('ts', 'desc')->take(Server::count());
    }])->get();
    

    There are 9 servers so we only get 9 results, 1 for each server