我创建了两次迁移,因为我想在dataList(dataNum) = dataList(dataNum).Insert(index, Item)
和Trend
之间建立一对一的关系。
TrendExplanation
这是Schema::create('trend_explanations', function (Blueprint $table) {
$table->increments('id');
$table->text('demographical')->nullable();
$table->text('economical')->nullable();
$table->text('social')->nullable();
$table->text('technological')->nullable();
$table->text('ecological')->nullable();
$table->text('political')->nullable();
$table->timestamps();
});
模型的迁移:
Trend
所以在模型中我做了以下添加:
Schema::create('trends', function (Blueprint $table) {
$table->increments('id');
$table->integer('explanation_id')->unsigned();
$table->foreign('explanation_id')->references('id')->on('trend_explanations');
$table->string('name');
$table->date('date');
$table->text('description');
$table->timestamps();
});
当然我创建了一个播种机来测试它:
class Trend extends Model
{
public function explanation()
{
return $this->hasOne(TrendExplanation::class);
}
}
当我运行它时,我收到错误:$trend = new Trend();
$trend->name = "Something";
$trend->description = "Description";
$explanation = new TrendExplanation();
// ...
$trend->explanation()->save($explanation);
$trend->save();
。
这是怎么发生的?我不明白我在这里做错了什么。
答案 0 :(得分:2)
指定关系时,可以指定外键和本地键。它通常是
$this->hasOne(Class, foreign, local);
所以你的定义是:
return $this->hasOne(TrendExplanation::class, 'id', 'explanation_id');