一对多关系 Laravel 无法显示相关数据

One to Many Relationship Laravel cannot display the related data

我有两个模型 DataKelurahanRegistrasiPasien 并且有一对多关系,但我无法访问该关系。

我制作了一个用于添加患者的表格并将其保存到 registrasi_pasiens table 并且效果很好。但是当我尝试显示关系数据时,它无法正常工作。

registrasi_pasiens table 中,我有 1 条记录 kelurahan_id = 3。然后,我尝试使用以下命令通过 php artisan tinker 访问它:

  1. $kelurahan = App\Domain\DataKelurahan\Models\DataKelurahan::find(3) 工作正常,数据存在。
  2. $pasien = App\Domain\RegistrasiPasien\Models\RegistrasiPasien::find(2007000001) 工作正常并且数据存在 kelurahan_id = 3
  3. $kelurahan->pasiens 结果是 null。它不应该显示 kelurahan_id = 3 的 pasien 数据吗?
  4. $kelurahan->pasiens->nama 结果是这样的 PHP Notice: Trying to get property 'nama' of non-object in D:/PROFESSIONAL/PROJECT/WEB DEVSeval()'d code on line 1 => null

我不知道我的代码有什么问题。非常感谢你们的帮助。

以下是我制作的模型:

DataKelurahan.php

<?php

namespace App\Domain\DataKelurahan\Models;

use Illuminate\Database\Eloquent\Model;
use App\Domain\RegistrasiPasien\Models\RegistrasiPasien;

class DataKelurahan extends Model
{
  protected $fillable = ['nama_kelurahan', 'nama_kecamatan','nama_kota'];
  public function pasiens(){
    return $this->hasMany('RegistrasiPasien');
  }
}

RegistrasiPasien.php

<?php

namespace App\Domain\RegistrasiPasien\Models;

use Illuminate\Database\Eloquent\Model;
use App\Domain\DataKelurahan\Models\DataKelurahan;

class RegistrasiPasien extends Model
{
    protected $fillable = [
      'nama',
      'alamat',
      'telepon',
      'rt',
      'rw',
      'tgl_lahir',
      'jenis_kelamin'
    ];

    public function kelurahan(){
      return $this->belongsTo('DataKelurahan');
    }
}

下面是我的数据库 tables:

data_kelurahans

Schema::create('data_kelurahans', function (Blueprint $table) {
   $table->increments('id');
   $table->string('nama_kelurahan');
   $table->string('nama_kecamatan');
   $table->string('nama_kota');
   $table->timestamps();
});

registrasi_pasiens

Schema::create('registrasi_pasiens', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('kelurahan_id')->unsigned();
   $table->string('nama');
   $table->string('alamat');
   $table->char('telepon', 15);
   $table->integer('rt');
   $table->integer('rw');
   $table->date('tgl_lahir');
   $table->string('jenis_kelamin');
   $table->timestamps();
});

Schema::table('registrasi_pasiens', function (Blueprint $table){
   $table->foreign('kelurahan_id')->references('id')->on('data_kelurahans')->onDelete('cascade');
});

来自Docs

Eloquent will automatically determine the proper foreign key column on the model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id.

所以,Eloquent 可能弄错了你的外键名称,所以你必须通过向 hasMany/belongsTo 方法传递额外的参数来覆盖外键:

public function pasiens(){
  return $this->hasMany('RegistrasiPasien','kelurahan_id');
}

public function kelurahan(){
  return $this->belongsTo('DataKelurahan','kelurahan_id');
}