首页 > 解决方案 > 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();
});

标签: laravel

解决方案


首先,方法的名称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


推荐阅读