laravel - Laravel 更新有很多关系
问题描述
我刚刚阅读了更多有关此问题的文档和问题以解决该问题,但对我来说没有任何用处,我有 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();
});
解决方案
首先,方法的名称months()
应该重命名为,month
因为它返回的是单个月而不是多个月。
其次,如果您Lesson
有一个名为的领域,month_id
那么它比您想象的要简单得多。我们可以改变这两行:
$lesson = Lesson::find($lesson->id);
$lesson->months()->associate($month)->save();
到以下行:
$lesson->update(['month_id' => $month->id);
它应该将month_id
您$lesson
的更新为$month->id
推荐阅读
- html - 图像未显示在用 HTML 编写的代码中
- python-3.x - 将 datetime.datetime 转换为 pandas 中的时间戳
- mysql - 使用 CURSOR/LOOP 从存储过程中返回单个集合中的数据
- python - Pandas 获得字符串之间距离最小的行(最接近的匹配)
- isabelle - 归纳谓词、传递闭包和代码生成
- python - 当我尝试在 conda 环境中运行 python2 文件时,g++ 不支持“-ffast-math -march=native”参数
- javascript - Onclick 图像按钮 - 逻辑没有意义
- python - 如何在不同文件中保存和加载 Sklearn 模型
- node.js - 为什么 NodeJS 中没有删除特定的数组?
- firebase - 使用firestore向前和向后跳转分页