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

Laf*_*une 2 php laravel

我正在尝试遍历一组 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;
Run Code Online (Sandbox Code Playgroud)

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

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

por*_*s Ψ 5

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

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

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

但是要返回响应:

The Response content must be a string or object implementing __toString()
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');
Run Code Online (Sandbox Code Playgroud)

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

->where('schedule_id', $schedule->id)->get()
Run Code Online (Sandbox Code Playgroud)