jeudi 19 janvier 2017

Laravel 5.3 whereIn from existing collection - optimise

I have a table with test dates (Test) and a table with results for each of those test dates (Results). I first get all the Test records for a particular athlete/customer. Then I need to get all the results for each of those test records. I only manage to get it working with a foreach loop. 1. Is there a more optimal way to structure the query? 2. For blade, is it perhaps more structured to have the array ordered per test_id? In blade I display the test data as headers and the results for each of those underneath.

First option below with sub query doesn't work. Get a db table not found error:

$athlete_tests = Test::where('athlete_id', $an_athlete->id)->get();
    if($athlete_tests){
        $results = Result::whereIn('test_id', function($query) use ($an_athlete){
                    $query->select('test_id')
                        ->from('Test')
                        ->where('athlete_id', $an_athlete->id);
                })->get();   
    }                 

This one works - must be optimised:

$athlete_tests = Test::where('athlete_id', $an_athlete->id)->get();
    if($athlete_tests){
        $results = collect([]);

        foreach ($athlete_tests as $key => $value) {
            $results = $results->merge(Result::where('test_id', $value->id)->get());
        }                    
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iXXuuU
via IFTTT

Aucun commentaire:

Enregistrer un commentaire