Laravel 5.7。我有两个模型,Foo
和Content
。它们的关系是多态的,因为Content
也可以与其他模型相关:
class Foo extends Model
{
public function contents()
{
return $this->morphToMany('App\Content');
}
}
class Content extends Model
{
use LastModified;
public function foos()
{
return $this->morphedByMany('App\Foo');
}
}
无论何时更新touch
模型,我都想Foo
模型Content
。因此,我对LastModified
模型使用了Content
特征:
trait LastModified
{
protected static function bootLastModified()
{
static::updating(function ($model) {
static::updateLastModified($model);
});
}
protected static function updateLastModified($model)
{
$foos = $model->foos;
if (count($foos) > 0) {
foreach ($foos as $foo) {
$foo->touch();
}
}
}
}
我的问题是$model->foos
返回正确的Foo
模型,但是返回了错误的id
。每个Foo
都有数据透视表行的Foo
,而不是id
自己的模型ID。这意味着触摸了错误的Foo
行。
答案 0 :(得分:1)
Laravel具有touching parent timestamps的内置功能。</ p>
在内容模型上,您可以添加一个属性,以告知在更新给定模型时应该建立的关系touched。
以下方法应该起作用:
class Content extends Model
{
protected $touches = ['foos'];
public function foos()
{
return $this->morphedByMany('App\Foo');
}
}
编辑:由于您使用的是静态更新事件,因此您应该从$model->touchOwners()
手动调用static::updated