移民人數表:
Schema::create('persons', function (Blueprint $table) {
$table->id();
$table->string("firstname");
$table->string("lastname");
$table->timestamps();
});
移民護照表:
Schema::create('passports', function (Blueprint $table) {
$table->id();
$table->string("identifystring")->unique();
$table->unsignedBigInteger("person_id");
$table->timestamps();
$table->foreign("person_id")->references("id")->on("persons")->onDelete("cascade");
});
人物模型:
class Person extends Model
{
use HasFactory;
protected $table ="persons";
protected $fillable = [
"firstname",
"lastname"
];
public function passport() {
$this->hasOne(\App\Models\Passport::class, "passports.person_id","persons.id");
}
}
護照型號:
class Passport extends Model
{
use HasFactory;
protected $table = "passports";
protected $fillable = [
"identifystring",
"person_id"
];
}
執行代碼:
$person = \App\Models\Person::findOrFail(2);
dd($person->passport());
結果是:空
uj5u.com熱心網友回復:
class Person extends Model
{
use HasFactory;
protected $table ="persons";
protected $fillable = [
"firstname",
"lastname"
];
public function passport() {
$this->hasOne(\App\Models\Passport::class, "person_id", "id");
}
}
uj5u.com熱心網友回復:
您沒有回傳關系。只需回傳它:
public function passport() {
return $this->hasOne(\App\Models\Passport::class, "passports.person_id","persons.id");
}
uj5u.com熱心網友回復:
根據撰寫的遷移。在 Person 模型中寫
public function passport() {
return $this->hasOne(\App\Models\Passport::class, "person_id","id");
}
并在 Passport 模型中寫入
public function person() {
return $this->belongsTo(\App\Models\Person::class, 'id', 'person_id');
}
執行代碼
$person = \App\Models\Person::findOrFail(2)->passport;
dd($person);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435154.html
