Laravel 一对一关系获取对象结果为 null
移民人员表:
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());
结果为:null
Migration persons Table:
Schema::create('persons', function (Blueprint $table) {
$table->id();
$table->string("firstname");
$table->string("lastname");
$table->timestamps();
});
Migration passports Table:
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");
});
Person model:
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");
}
}
Passport Model:
class Passport extends Model
{
use HasFactory;
protected $table = "passports";
protected $fillable = [
"identifystring",
"person_id"
];
}
execute Code:
$person = \App\Models\Person::findOrFail(2);
dd($person->passport());
Result is: null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您没有返回该关系。只需返回它:
You did not return the relation. just return it:
根据所写的迁移。在 Person 模型中编写
并在 Passport 模型中编写
执行代码
As per the migrations written. In the Person model write
and in the Passport model write
Execute the code
使用此代码。
在你的个人模型中
在你的护照模型中
然后尝试通过做同样的事情再次传递关系
Use this code.
In your Person Model
In your passport model
Then try to pass the relation again by doing the same thing