【问题标题】:How to use objects in where clause in Laravel SQL query如何在 Laravel SQL 查询的 where 子句中使用对象
【发布时间】:2018-12-15 16:03:30
【问题描述】:

假设我有一些doctor_id的对象数据

{doctor_id: 1} 
{doctor_id: 2}

现在我想从doctors 表中找到那些被选中的doctor_id 的名字。

doctors 表字段为id,name,address....

我的查询是

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

但我从 log 文件中收到错误

local.ERROR: SQLSTATE[HY000]: 一般错误: 2031 (SQL: select * from doctors where id in (?))

对此的查询是什么。请帮忙

【问题讨论】:

  • 对象数据,集合吗?
  • @linktoahref...是的...
  • 你能显示结果吗dd($doctor_id);

标签: php mysql sql laravel laravel-5.5


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

    您可以使用pluck 方法获取给定键的值数组,您可以将其作为第二个参数传递给whereIn 方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2011-12-03
      • 1970-01-01
      • 2021-09-18
      • 2021-05-05
      • 1970-01-01
      相关资源
      最近更新 更多