简体   繁体   中英

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

$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:

$mtn->observation

it gives me null; and in the Database there is no observation ID in the observation_id field;

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. Therefore, both activity and observation relations in MeetingTest should return $this->belongsTo instead of $this->hasOne

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM