如何在Laravel中优化代码? [英] How to optimize code in Laravel?

查看:73
本文介绍了如何在Laravel中优化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从两个相关表中获取数据:

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;

结果这部分代码我得到了一个带有key => value的数组,以将其插入到Blade模板的选择列表中.

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

但是我想逃避循环:

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?

推荐答案

您可以使用Laravel Collections https ://laravel.com/docs/5.3/collections

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

这篇关于如何在Laravel中优化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆