[英]Laravel update hasMany relationship
我剛剛閱讀了更多關於這個問題的文檔和問題來解決這個問題,但是沒有什么對我有用,我有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();
因為我嘗試在數據庫中的Lesson
表上更改month_id
列,例如$month->id
value,我該怎么做?
更新:
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();
});
首先,方法months()
的名稱應該重命名為month
因為它返回單個月而不是多個月。
其次,如果你的Lesson
有一個名為month_id
的字段,那么它比你month_id
的要簡單得多。 我們可以改變這兩行:
$lesson = Lesson::find($lesson->id);
$lesson->months()->associate($month)->save();
到以下行:
$lesson->update(['month_id' => $month->id);
它應該將$lesson
的month_id
更新為$lesson
month_id
$month->id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.