jeudi 3 mai 2018

How to eager load relationships at the time i query the parent model using Laravel

I have a Adress table and a Kontokorrent table. I need to return them and show on google maps.

this is my controller:

$addresses = Address::whereHas('kontokorrent', function($query) {
            $query->ktoArt('D')->mandant(1)->aktiv();
        });

        //Conditional                
        if(!! Auth::user()->activeAddress) {
            $addresses->where('Aktiv', '<>', 0); 
        }


         $addressesFormated = $addresses->get()->map(function($item, $key) {
             return [
                  'addresse' => $item->Adresse,
                  'kto' => $item->kontokorrent->Kto,
                  'name' => $item->Name1,
                  'anschrift' => ['strasse' => $item->LieferStrasse, 'plz' => $item->LieferPLZ, 'ort' => $item->LieferOrt, 'land' => $item->LieferLand],
                  'telefon' => $item->Telefon,
                  'email' => $item->Email,
                  'coords' => ["lat" => $item->USER_CCgeoLatitude, "lng" => $item->USER_CCgeoLongitude],
                  'umsatz' => number_format(Umsatz::year($item->kontokorrent->Kto, date('Y')),2),
                  'vorjahresUmsatz' => number_format(Umsatz::year($item->kontokorrent->Kto, date('Y')-1),2),
                  'letzteBestellung' => \Carbon\Carbon::parse($item->kontokorrent->LetzterUmsatz)->toDateString()           
             ];
         });
 dd($addressesFormated);

i'm iterating through the collection and passes each value as key=>value. This is working but is very slow. I need >30sec when i'm interating over 10k rows.

maybe i should use the eager loading to increase the performence.

unfortunely i'm getting no relation

relations: array:1 [ "kontokorrent" => null ]

in array when i try this in my controller:

$addresses = $addresses->with('kontokorrent:Kto')->take(10)->get(['Name1', 'LieferStrasse', 'LieferLand', 'LieferOrt', 'LieferPLZ', 'Telefon', 'EMail', 'USER_CCgeoLatitude', 'USER_CCgeoLongitude']);

        dd($addresses);

i have also tried to put the Kto into the ->get() function. But i get an error.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire