简体   繁体   English

laravel toArray() 耗时太长

[英]laravel toArray() taking too long

I have this code, and I'm trying to populate an json because this is an API.我有这个代码,我正在尝试填充一个 json,因为这是一个 API。

$mids   = Message::where('sender', $user)
                    ->orWhere('receipient', $user)
                    ->lists('mid');

$last   = Message::whereIn('mid', $mids)->orderBy('mid', 'desc')->first();
$final  = $last->toArray();
return $final;

If I dont make the $last to array then it will just return something like:如果我不将 $last 设置为数组,那么它只会返回如下内容:

"incrementing": true,
"timestamps": true,
"exists": true

But when I add the toArray() function it just keeps loading and loading until the server says execution time exceeded.但是当我添加 toArray() 函数时,它只会继续加载和加载,直到服务器说超出执行时间。 Why?为什么?


additional info附加信息

This code is in a model and its getLastMsgAttribute and I appends last_msg这段代码在一个模型和它的getLastMsgAttribute ,我附加了last_msg

As @naththedeveloper mentioned toArray will determine the attributes and relations that need to be retrieved in order to convert the collection to a model.正如@naththedeveloper 提到的, toArray 将确定需要检索的属性和关系,以便将集合转换为模型。 Our issue was that we had 3 mutators on the Model (eg getSomeAttribute), one of them was performing a DB query for each model which meant 2000 queries (all of which were actually duplicates).我们的问题是我们在模型上有 3 个 mutator(例如 getSomeAttribute),其中一个是为每个模型执行数据库查询,这意味着 2000 个查询(所有这些实际上都是重复的)。

So check your attributes and relations所以检查你的属性和关系

Also look into resources as I think this allows you to define your own toArray method so you can select only the fields you need for your final array.还要查看资源,因为我认为这允许您定义自己的 toArray 方法,以便您只能选择最终数组所需的字段。

You might also be able to just use Laravel's collection "pluck" method.您也可以只使用 Laravel 的集合“pluck”方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM