【发布时间】:2019-03-05 03:39:38
【问题描述】:
在我的网络应用程序中,我有 2 个模型,分别是 month 和 lessons,month 是 hasMany 和 lessons。
这意味着每个课程记录都属于month 表,每个month hasMany lesson,现在这是我的模型
class Month extends Model
{
protected $table = 'months';
protected $guarded = ['id'];
public function lessons()
{
return $this->hasMany(Lessons::class);
}
}
class Lessons extends Model
{
protected $table = 'section_lessons';
protected $guarded = ['id'];
public function month()
{
return $this->belongsTo(Month::class);
}
}
现在我正在尝试将简单记录保存为与此代码的关系:
$month = new \App\Entities\Month;
$month->section_month_name = '';
$month->month_title = '';
$month->section_price = '';
$month->section_available = true;
$month->lessons_count = '';
$month->image = '';
//$month = $month->save();
$lesson = new \App\Entities\Lessons;
$lesson->title = '';
$lesson->content = '';
$lesson->file_url = '';
$lesson->filename = '';
$lesson->time = '';
$lesson->media = '';
$lesson->course = true;
//$lesson->save();
$month->lessons()->save($lesson);
$month->save();
我得到这个错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'month_id' in 'field list' (SQL: insert into `section_lessons` (`title`, `content`, `file_url`, `filename`, `time`, `media`, `course`, `month_id`, `updated_at`, `created_at`)
迁移类:
class Months extends Migration
{
public function up()
{
Schema::create('months', function (Blueprint $table) {
$table->increments('id');
$table->string('section_month_name');
$table->string('month_title');
$table->string('section_price');
$table->boolean('section_available');
$table->integer('lessons_count');
$table->text('image');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('months');
}
}
class Lessons extends Migration
{
public function up()
{
Schema::create('section_lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('months_id')->unsigned();
$table->foreign('months_id')->references('id')->on('months')->onDelete('cascade');
$table->string('title');
$table->string('content');
$table->string('file_url');
$table->string('filename');
$table->string('time');
$table->string('media');
$table->boolean('course', false);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('section_lessons');
}
}
【问题讨论】:
-
请发送
dd($month)并告诉我们你得到了什么。 -
@LucasPiazzi 我的帖子已更新
-
请在发布问题之前仔细阅读此文档laravel.com/docs/5.7/eloquent-relationships
-
先保存
$month,然后保存关系 -
您可以尝试将
section_lessons表中的months_id更改为month_id吗?
标签: laravel