我有两个型号Job
和User
。
用户可以被分配许多作业,并且作业可以有许多受让人。
class Job extends Model {
public function assignees()
{
return $this->belongsToMany('AppModelsUser')->withTimestamps();
}
}
class User extends Model {
public function jobs()
{
return $this->belongsToMany('AppModelsJob')->withTimestamps();
}
}
在我的工作控制器中,我正在更新受让人,如下所示:
$job = Job::find(1);
$job->assignees()->sync([1,2]);
$job->save();
除了作业的时间戳没有更新之外,一切都按预期进行。
updated_at
字段保持不变。
有人能看到我的问题在哪里吗?
参考文档,这应该完成以下工作:https://laravel.com/docs/7.x/eloquent-relationships#touching-父时间戳
您的模型应该包括一个新的数组属性$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('AppModelsUser')->withTimestamps();
}
}
class User extends Model {
protected $touches = ['jobs'];
public function jobs()
{
return $this->belongsToMany('AppModelsJob')->withTimestamps();
}
}
BTW:withTimestamps()
-方法只更新中间表的时间戳。
您可以在$job->assignees()->sync([1,2]);
行之后使用$job->touch();
,如下所示:
$job = Job::find(1);
$job->assignees()->sync([1,2]);
$job->touch();
$job->save();
这将为您更新时间戳。