【问题标题】:Laravel - How to Resolve Object of class stdClass could not be converted to string ErrorLaravel - 如何解决类 stdClass 的对象无法转换为字符串错误
【发布时间】:2020-02-20 03:27:09
【问题描述】:

当我运行这段代码时:

   public function manager_employee_list()
   {
       $userCompany = Auth::user()->company_id;
       $userEmployee = Auth::user()->employee_id;
       $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();

       $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
       $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();  
       $goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id', 
       return view('appraisal.appraisal_goals.manager_employee_list')->with('goals', $goals);        
}

我收到了这个错误:

stdClass 类的对象无法转换为字符串

当我这样做时:

dd($linemanageremployee);

我明白了:

Illuminate\Support\Collection {#880 ▼
  #items: array:3 [▼
    0 => {#2312 ▼
  +"id": 2
}
1 => {#2326 ▼
  +"id": 3
}
2 => {#2313 ▼
  +"id": 6
    }
  ]
}

我该如何解决?

谢谢。

【问题讨论】:

  • Try the docsget() 返回一个集合,正如您的 dd() 所示。集合就像一个数组——不是一个东西,而是一组东西。在您的示例中,您的数据库查询返回 3 ids。您需要遍历集合中的每个项目才能使用它们。

标签: laravel


【解决方案1】:

尝试改变:

$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();

$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');

然后改变:

$goals = AppraisalGoal::where('employee_id', $linemanageremployee) ...

$goals = AppraisalGoal::whereIn('employee_id', $linemanageremployee) ...

说明:

->get() 方法返回一个 Eloquent 集合,不能直接在 where() 内部进行查询。

->pluck()方法返回一个数组,可以用它来查询whereIn()

【讨论】:

  • 这可能是答案,但它对 OP 和未来的访问者会更有帮助,并解释您做了什么以及为什么
猜你喜欢
  • 2017-09-21
  • 2017-07-25
  • 1970-01-01
  • 2021-11-09
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 2014-11-21
相关资源
最近更新 更多