How to optimize code in Laravel?

倖福魔咒の 提交于 2020-01-11 07:49:09

问题


I use the following code to get data from two related tables:

$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;

$subcategories = $objectModel::with("translate", "parent")->get();

foreach($subcategories as $key => $item) {
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}

array_unshift($arr, 'Select category');
return $arr;

In result this part of code I get array with key => value to insert this in select list in Blade template.

But I desire to escape a loop:

foreach($subcategories as $key => $item) {
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}

And get clear collection from request. How can I do it?


回答1:


You can use Laravel Collections https://laravel.com/docs/5.3/collections

$arr = ProductCategory::with("translate", "parent")->get()
            ->mapWithKeys(function ($item, $key) {
                return [$item->translate()->first()->objectId => $item->translate()->first()->name];
            })
            ->all();


来源:https://stackoverflow.com/questions/39759114/how-to-optimize-code-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!