Table hasOne 关系未创建

Table hasOne relation not being created

我有一个 tables table 模型定义如下:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Table extends Model
{
    public function location()
    {
        return $this->hasOne('App\Location');
    }
}

我有一个 locations table 和 table_id 列,模型定义如下:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Location extends Model
{
    public function table()
    {
        return $this->belongsTo('App\Table');
    }
}

我在数据库中植入了一个示例位置,该位置的 id1。在我的控制器中,在 DB::transaction 块中,我 运行 以下代码:

$table = new Table;
$location = Location::findOrFail(1);
$table->location()->save($location);
$table->saveOrFail();

此代码 运行s 没有错误,但是,当我查看数据库时,我所在位置的 table_id 列仍然是空的。我做错了什么?

我也尝试了以下方法,但无济于事:

$table = new Table;
$location = Location::findOrFail(1);
$table->saveOrFail();
$location->table()->associate($table);

只有以下方法有效:

$table = new Table;
$table->save();
$location = Location::findOrFail(1);
$location->table_id = $table->id;
$location->save();

你反其道而行之。尝试以下操作:

$table = new Table;
$location = Location::findOrFail(1);
$location->table()->associate($table);
$location->save();

你真正需要做的是将实例的外键关联到一个新对象,外键在Location模型中。