如何在使用Laravel查询父模型时急切加载关系

时间:2018-05-03 10:54:41

标签: php laravel-5

我有一张地址表和一张Kontokorrent表。我需要退回它们并在谷歌地图上显示。

这是我的控制者:

$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);

我遍历集合并将每个值传递为key=>value。 这很有效,但速度很慢。当我进行超过10k行的交互时,我需要> 30秒。

也许我应该使用急切加载来提高性能。

不幸的是我没有关系

  关系:数组:1 [           &#34; kontokorrent&#34; =&GT;空值         ]

当我在我的控制器中尝试这个时,

在数组中:

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

        dd($addresses);

我还尝试将Kto放入->get()函数中。但是我得到了一个错误。

1 个答案:

答案 0 :(得分:1)

您必须包含所需的外键列:

$addresses->with('kontokorrent:Adresse,Kto')
相关问题