我有两个名为DataKelurahan
和RegistrasiPasien
的模型,并且具有一对多关系,但是我无法访问该关系。
我制作了一个添加患者的表格并将其保存到registrasi_pasiens
表中,并且效果很好。但是当我尝试显示关系数据时,它无法正常工作。
在registrasi_pasiens
表中,我有1条kelurahan_id = 3
的记录。然后,我尝试使用以下命令通过php artisan tinker
访问它:
$kelurahan = App\Domain\DataKelurahan\Models\DataKelurahan::find(3)
正常工作并且存在数据。$pasien = App\Domain\RegistrasiPasien\Models\RegistrasiPasien::find(2007000001)
工作正常,并且数据与kelurahan_id = 3
存在$kelurahan->pasiens
的结果是null
。它不应该显示具有kelurahan_id = 3的pasien数据吗?$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');
}
}
下面是我的数据库表:
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');
});
答案 0 :(得分:1)
来自Docs:
Eloquent将自动确定适当的外键列 该模型。按照惯例,口才是“蛇皮案” 拥有模型的名称,并在其后缀
_id
。
因此,口才很强的外键名称可能是错误的,因此您必须通过将其他参数传递给hasMany
/ belongsTo
方法来覆盖外键:
public function pasiens(){
return $this->hasMany('RegistrasiPasien','kelurahan_id');
}
public function kelurahan(){
return $this->belongsTo('DataKelurahan','kelurahan_id');
}