How to optimize code in Laravel?

2019-02-21 01:28发布

问题:

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