Php Laravel:类Illumb\Database\Eloquent\Builder的对象无法转换为字符串
我试图循环通过一个id数组从另一个表中获取数据,我的意思是,我想获取我们在其中循环的每个计划id的最新队列 因此,首先我有$时间表: $schedules=[{“id”:19},{“id”:18},{“id”:15}] foreach循环是这样的:Php Laravel:类Illumb\Database\Eloquent\Builder的对象无法转换为字符串,php,laravel,Php,Laravel,我试图循环通过一个id数组从另一个表中获取数据,我的意思是,我想获取我们在其中循环的每个计划id的最新队列 因此,首先我有$时间表: $schedules=[{“id”:19},{“id”:18},{“id”:15}] foreach循环是这样的: $queues= []; foreach ($schedules as $schedule) { $queues[] = Queue::withTrashed() ->latest()
$queues= [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule);
}
return $queues;
当我返回队列时,它显示:
无法将Illumb\Database\Eloquent\Builder类的对象转换为字符串
可能是因为您没有从查询中获得结果。因为它只是一个查询,所以它将返回一个查询对象。您需要添加
->get()
以获得结果。您可以尝试以下代码:
$queues = [];
foreach ($schedules as $schedule) {
$queues[] = Queue::withTrashed()
->latest()
->where('schedule_id', $schedule)->get()->toArray();
}
return $queues;
显示的错误与您未运行查询有关,您需要在
队列::…->where(…)->get()
的末尾添加一个->get()
,才能执行此操作
如果你不这样做,正如Dhananjay Kyada在回答中所说:
它将尝试返回一个查询对象
但要回应:
The Response content must be a string or object implementing __toString()
接下来,我们还需要解决一件事
如果要定义变量$schedules
,并按问题中所示为其赋值:
$schedules=[{“id”:19},{“id”:18},{“id”:15}]
尝试将JSON作为字符串,并使用以下命令将其转换为PHP变量:
然后可以在where子句中使用id值:
->where('schedule_id', $schedule->id)->get()
您正在定义
$queueses=[]然后您使用的是$queues[]=Queue::…
。这是打字错误吗?另外,您没有运行查询,您需要在队列的末尾添加一个->get()
:…->where(…)->get()
谢谢,但是我还有一个问题,就是只能获取空的方括号,当我删除->where('schedule_id',$schedule)时,这会起作用,但会获取我不想要的数据。这行代码@porloscerrosψ有什么问题,请尝试使用->where('schedule_id',$schedule->id)代码>嗯,我认为这行不通,它只是变得更糟,它说试图获取非对象的属性“id”
。那会出现吗@porloscerrosψ如果定义变量$schedules
并按问题中所示为其赋值,请尝试这样做:$schedules=json_decode(“[{id:19},{id:18},{id:15}”)代码>
->where('schedule_id', $schedule->id)->get()