簡體   English   中英

如何更新多對多關系中的時間戳

[英]How do you update the timestamps in a many-to-many relationship

我有兩個模型JobUser

可以為用戶分配許多工作,並且工作可以有多個受讓人。

class Job extends Model {

  public function assignees()
  {
    return $this->belongsToMany('App\Models\User')->withTimestamps();
  }

}


class User extends Model {

  public function jobs()
  {
      return $this->belongsToMany('App\Models\Job')->withTimestamps();
  }

}

在我的工作 Controller 中,我正在像這樣更新受讓人:

$job = Job::find(1);

$job->assignees()->sync([1,2]);

$job->save();

除了作業的時間戳沒有更新外,一切都按預期工作。

updated_at字段保持不變。

誰能看到我的問題可能出在哪里?

參考文檔,這應該可以完成工作: https://laravel.com/docs/7.x/eloquent-relationships#touching-parent-timestamps

您的模型應該包含一個新的數組屬性$touches ,它會獲取一個帶有關系名稱的新項目。

class Job extends Model {

  //if you also want to update a user model from the jobs site
  protected $touches = ['assignees'];

  public function assignees()
  {
    return $this->belongsToMany('App\Models\User')->withTimestamps();
  }

}


class User extends Model {

  protected $touches = ['jobs'];

  public function jobs()
  {
      return $this->belongsToMany('App\Models\Job')->withTimestamps();
  }

}

順便說一句: withTimestamps() - 方法僅更新中間表的時間戳。

您可以使用$job->touch(); $job->assignees()->sync([1,2]); 像這樣的行:

$job = Job::find(1);
$job->assignees()->sync([1,2]);
$job->touch();
$job->save();

這將為您更新時間戳。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM