如何在 Laravel SQL 查询中的 where 子句中使用对象

How to use objects in where clause in Laravel SQL query

假设我有一些 doctor_id

的对象数据
{doctor_id: 1} 
{doctor_id: 2}

现在我想从 doctors table.

中找到那些被选中的 doctor_id 的名字

doctors table 字段是 id,name,address...

我的查询是

$doctors_data = Doctor::whereIn('id', $doctor_id)->get();

但是我从 log 文件中得到错误

local.ERROR: SQLSTATE[HY000]: General error: 2031 (SQL: select * from doctors where id in (?))

这是什么查询。请帮忙

您可以使用 pluck method, which you could pass as second argument to the whereIn 方法

获取给定键的值数组
$doctorids = $doctorscollection->pluck('doctor_id');
$doctors_data = Doctor::whereIn('id', $doctorids)->get();

whereIn 要求第二个参数是一个数组。

即在你的情况下,wherein 应该是这样的。

$doctorsData = Doctor::whereIn('id', [1,2])->get();

不确定你的 $docter_id 中有什么类型的对象,但你的问题的解决方案是,你需要先将你的对象转换为一个 id 数组,然后再将其输入 whereIn.

希望你明白了。如果仍然无法解决问题,您可以将您的 doctor_id 对象分享给我们,以便我们帮助将其转换为数组。