[英]One-To-One Eloquent Relationship functions
There is something I miss in the eloquent one-to-one relationship: 雄辩的一对一关系让我有些想念:
class MeetingTest extends Model
{
protected $table = 'meeting_tests';
public function meeting() {
return $this->belongsTo('App\Meeting','meeting_id','id');
}
public function observation() {
return $this->hasOne('App\Observation','meeting_test_id','id');
}
public function activity() {
return $this->hasOne('App\TestActivity','activity_id','id');
}
}
The Observation Class is 观察课是
class Observation extends Model
{
protected $table = 'observations';
public function meetingTest() {
return $this->belongsTo('App\MeetingTest','meeting_test_id','id');
}
}
If I run php artisan tinker and 如果我运行php artisan tinker和
$mtn = App\MeetingTest::create();
$mtn->save();
$ob = App\Observation::create();
$ob->save;
$mtn->observation()->save($ob);
At this point inside the Observation record I can see the meeting_test_id filled with the correct id of the meetingTest, but if I try: 此时,在观察记录中,我可以看到Meeting_test_id充满了MeetingTest的正确ID,但是如果尝试:
$mtn->observation $ mtn->观察
it gives me null; 它给了我空; and in the Database there is no observation ID in the observation_id field; 在数据库中,observation_id字段中没有观察ID;
this is the migration: 这是迁移:
Schema::create('meeting_tests', function (Blueprint $table) {
$table->increments('id');
$table->integer('meeting_id')->unsigned();
$table->integer('observation_id')->unsigned()->nullable();
$table->integer('activity_id')->unsigned()->nullable();
$table->timestamps();
});
I don't understand what is not correct. 我不明白什么是不正确的。
I can see observation_id and activity_id in your meeting_tests table, which makes records in this table the owned side of one-to-one/one-to-many relation. 我可以在Meeting_tests表中看到observation_id和activity_id ,这使该表中的记录成为一对一/一对多关系的拥有方。 Therefore, both activity and observation relations in MeetingTest should return $this->belongsTo instead of $this->hasOne 因此, MeetingTest中的 活动和观察关系都应返回$ this-> belongsTo而不是$ this-> hasOne
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.