php - 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 类的对象无法转换为字符串
解决方案
显示的错误与您没有运行查询有关,您需要->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()
推荐阅读
- python-3.x - 如何在循环内按类别打印预测
- javascript - 防止在基本银行应用程序上重置总数
- java - 如何在 JavaFX 中使一个区域与另一个区域相等?
- arrays - 如何在 Core Data iOS Swift 中删除和更新结构类型数组?
- flask - 当我通过 conda 安装烧瓶时,它会抛出错误 [PermissionError 13, Permission Denied]?
- javascript - 更深入地理解 React 事件冒泡/传播和状态管理
- r - Finalfit:将 summary_factorlist 与多变量 cox 模型合并后的格式表
- javascript - countDocuments() 在 api 调用中不起作用
- excel - 将两个单元格与 Excel 中的其他两个单元格进行比较
- javascript - 如何在参数中设置组合键