【问题标题】:Laravel update hasMany relationshipLaravel 更新有很多关系
【发布时间】: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


【解决方案1】:

首先,方法名称months() 应该重命名为month,因为它返回的是单月而不是多月。

其次,如果您的 Lesson 有一个名为 month_id 的字段,那么它比您想象的要简单得多。我们可以改变这两行:

$lesson = Lesson::find($lesson->id);
$lesson->months()->associate($month)->save();

到下面一行:

$lesson->update(['month_id' => $month->id);

它应该将您的$lessonmonth_id 更新为$month->id

【讨论】:

  • 你能看看我更新的帖子吗?它不适合我
猜你喜欢
  • 1970-01-01
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 2015-08-05
  • 2016-10-12
  • 1970-01-01
  • 2017-09-03
相关资源
最近更新 更多