从 laravel 中的多个表中选择

Selecting from multiple tables in laravel

请help.I进行如下测试预订table

Schema::create('test_bookings', function (Blueprint $table) {
        $table->unsignedInteger('RequestID');
        $table->string('bookingDate');
        $table->string('timeSlot');
        $table->unsignedInteger('nurse_id');
        $table->timestamps();
    });

和一个看起来像这样的测试table

Schema::create('tests', function (Blueprint $table) {
        $table->unsignedInteger('RequestID');
        $table->unsignedInteger('patientID');
        $table->string('barcode');
        $table->string('temperature');
        $table->string('pressure');
        $table->string('oxygen');
        $table->unsignedInteger('nurseID');
        $table->timestamps();
    });

仅当 test_bookings RequestID 在测试中 table 时,我想显示护士的 RequestID、预订日期、时间段、姓名和姓氏。这是我的护士table

Schema::create('nurses', function (Blueprint $table) {
        $table->unsignedInteger('nurseID');
        $table->string('name');
        $table->string('surname');
        $table->string('idNumber');
        $table->string('phone');
        $table->string('email');
        $table->unsignedInteger('suburb_id');
        $table->timestamps();


        $table->index('suburb_id');
    });

这是我试过的代码

$tests =  DB::table('tests')
                ->select('RequestID','bookingDate','timeSlot','name','surname')
                ->join('nurses','nurses.nurseID','test_bookings.nurse_id')
                ->join('test_bookings','test_bookings.RequestID','=','tests.RequestID')
                ->get();

but when I join the tests table nothing is showing

那是因为您正在使用 join clause that generate innerJoin statement, and to see the results you should use leftJoin

$tests =  DB::table('tests')
                ->select('RequestID','bookingDate','timeSlot','name','surname')
                ->leftJoin('nurses','nurses.nurseID','=','test_bookings.nurse_id')
                ->leftJoin('test_bookings','test_bookings.RequestID','=','tests.RequestID')
                ->get();

为什么你不在这里使用 ORM,一个简单的一对一关系可以完美地完成这项工作。这是一个例子:

class TestBooking extends Model {
 # Other code...
 public function nurse(){
    return $this->belongsTo(Nurse::class);
  }
}
class Test extends Model {
 # Other code...
 public function testBooking(){
    return $this->belongsTo(TestBooking::class, 'RequestID','RequestID');
  }
}

现在您可以像这样获取所有数据:

 $tests = Test::with("testBooking","testBooking.nurse")->get();
 // and get data inside loop like this:
 $test->RequestID // to get request ID
 $test->testBooking->bookingDate // to get booking date
 $test->testBooking->timeSlot // to get timeSlot
 $test->testBooking->nurse->name // to get nurse name
 $test->testBooking->nurse->surname // to get nurse surename

了解更多关系read documention