【发布时间】:2019-05-02 17:35:18
【问题描述】:
我刚刚阅读了有关此问题的更多文档和问题以解决该问题,但对我来说没有任何用处,我有 2 个带有此模型的表:
class Month extends Model
{
protected $guarded = ['id'];
public function lessons()
{
return $this->hasMany(Lesson::class);
}
}
class Lesson extends Model
{
protected $guarded = ['id'];
public function months()
{
return $this->belongsTo(Month::class);
}
}
我可以使用此示例代码保存一些与关系相关的数据,并且工作正常:
$month = Month::find(1);
$lesson = new Lesson();
$lesson->title = $request->title;
$lesson->content = $request->content;
$lesson->file_url = $uploadedFilePath;
$lesson->filename = $filename;
$lesson->time = $request->time;
$month = $month->lessons()->save($lesson);
现在我尝试使用此代码更新一些课程字段:
$lesson = Lesson::find($id);
$lesson->update([
'title' => $request->title,
'content' => $request->content,
'file_url' => $uploadedFilePath,
'filename' => $filename,
'time' => $request->time
]);
$month = Month::find($request->months['0']);
$lesson = Lesson::find($lesson->id);
$lesson->months()->associate($month)->save();
我尝试用例如$month->id 值更改数据库中Lesson 表上的month_id 列,我该怎么做?
更新:
class Lesson extends Model
{
protected $guarded = ['id'];
public function month()
{
return $this->belongsTo(Month::class);
}
}
控制器:
$lesson->update([
'title' => $request->title,
'content' => $request->content,
'file_url' => $uploadedFilePath,
'filename' => $filename,
'time' => $request->time
]);
$month = Month::find($request->months['0']);
$lesson = Lesson::find($lesson->id);
$lesson->month()->associate($month)->save();
$lesson->update(['month_id' => $month->id]);
迁移:
Schema::create('months', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
Schema::create('lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('month_id')->unsigned();
$table->string('title');
$table->longText('content');
$table->string('file_url');
$table->string('filename');
$table->string('time', 50);
$table->foreign('month_id')->references('id')->on('months')->onDelete('cascade');
$table->timestamps();
});
【问题讨论】:
-
你是否在同一个控制器中同时执行这两个保存?
标签: laravel