首页 > 解决方案 > Laravel:类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串

问题描述

我正在尝试遍历一组 id 以从另一个表中获取数据,我的意思是我想获取我们在其中循环的每个计划 id 的最新队列。

所以首先我有$schedules

$schedules = [{"id":19},{"id":18},{"id":15}]

而foreach循环是这样的:

$queues= [];
foreach ($schedules as $schedule) {
     $queues[] = Queue::withTrashed()
                     ->latest()
                     ->where('schedule_id', $schedule);
}
return $queues;

当我返回队列时,它显示:

Illuminate\Database\Eloquent\Builder 类的对象无法转换为字符串

标签: phplaravel

解决方案


显示的错误与您没有运行查询有关,您需要->get()在末尾Queue::...->where(...)->get()执行此操作。

如果你不这样做,正如 Dhananjay Kyada 在他的回答中所说:

它将尝试返回一个查询对象

但是要返回响应:

The Response content must be a string or object implementing __toString()

接下来,我们还需要解决一件事。

如果您正在定义变量$schedules并为其分配值,如问题中所示:

$schedules = [{"id":19},{"id":18},{"id":15}]

尝试将 JSON 作为字符串并使用json_decode将其转换为 PHP 变量:

$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');

然后您可以在 where 子句中使用 id 值:

->where('schedule_id', $schedule->id)->get()

推荐阅读