如何在 Laravel 中使用 FOREACH 从数据库中获取数据?

How to get data from a database using FOREACH in Laravel?

请问我有一个健康管理系统并尝试使用 foreach 从数据库中获取数据。 return 值是一个数组结果而不是两个。请通过我的代码。我需要帮助才能显示所有结果。

Controller.php

$result = \DB::table('patient_results')
        ->select('*')
        ->whereIn('test', $arraylistTable)
        ->where('patient_id', $id)
        ->where('specimen_id', $specimen_id)
        ->get();


        $testValue = $result->pluck('test'); //return values [ "KMS", "MLS"]
        
        foreach($testValue as $clinical_data) {

           return $Testdata = \DB::table('tests')
            ->select('*')
            ->where('test_name', $clinical_data)
            ->get();            
           // returns data for only "KMS" Instead of both. There exist a data for both "KMS", "MLS". How do I display them
        }

where 采用单个值。您正在寻找 whereIn,它将使用该数组进行搜索。它转换为 where test_name IN ('KMS','MLS')

->whereIn('test_name', $clinical_data)

它显​​示一条记录,因为您的循环中有 return 语句。 它在第一次执行时返回。

解决方案

  • 将所有记录组合成一个数组然后return

更好的解决方案

  • 应用两个表的连接或编写子查询。这将减少循环的开销。
$testValue = $result->pluck('test'); //return values [ "KMS", "MLS"]
$newArray = [];
array_push($testValue , $newArray);

   
        foreach($newArray as $clinical_data) {

           return $Testdata = \DB::table('tests')
            ->select('*')
            ->whereIn('$clinical_data', $newArray)
            ->get();            
           // returns data for only "KMS" Instead of both. There exist a data for both "KMS", "MLS". How do I display them
        }