我想在帖子恢复后恢复附加到帖子的评论。
这将失败:
public function restored(Post $post)
{
$post->comments()
->onlyTrashed()->where('deleted_at', '>=', $post->deleted_at)
->get()
->each(function ($comment) {
$comment->restore();
});
}
这有效:
public function restoring(Post $post)
{
$post->comments()
->onlyTrashed()->where('deleted_at', '>=', $post->deleted_at)
->get()
->each(function ($comment) {
$comment->restore();
});
}
区别是:restoring()
而不是restored()
。
以下条件:where('deleted_at', '>=', $post->deleted_at)
在这里,因为我不想恢复在删除帖子之前软删除的评论。换句话说,我不想恢复被版主软删除的评论。我想恢复在软删除帖子的那一刻被软删除的评论。
失败的原因:我相信它restored()
失败是因为$post->deleted_at
变得null
所以我不能再在where(...)
条件下使用它了。
问:如何在恢复之前保存以前的$post->deleted_at
值?我尝试玩getDirty()
和getChanges()
但这些都没有帮助,它们在观察器中没有跟踪以前的值。
我还尝试了以下方法:
public function restoring(Post $post)
{
$this->deleted_at = $post->deleted_at;
}
认为这将允许我"坚持"$post->deleted_at
的值,并能够在我的restored()
方法中使用它。但是没有。
我注意到restored()
只恢复了第一条评论。这就像一旦在某种循环中恢复了评论,然后$post->deleted_at
因为null
(显然,因为它是restored
而不是restoring
(,所以它无法继续恢复集合中的其他评论。我认为它会抛出错误,因为我想循环然后尝试像where('deleted_at', '>=', null)
一样做(注意"null"("。 果然,这确实有效:
public function restored(Post $post)
{
$post->comments()
->onlyTrashed()
->get()
->each(function ($comment) {
$comment->restore();
});
}
(请注意,这是restored()
但我不得不摆脱我的where(...)
,但我确实需要那个where(...)
条件(。
基本上和TL;DR:如何在我的public function restoring(Post $post) { }
内获得$post->deleted_at
的"旧"值(恢复前的值(
我不确定这是否是理想的方法,但它似乎在一些快速测试中有效。 如果您希望以这种方式与属互,还可以在 Post 模型中设置 getter 和 setter 方法。
后.php
class Post extends Model
{
// add a custom property with a unique name
// this will prevent the data from being assigned as an attribute
public $temp_deleted_at;
// ...
}
后观察者.php
public function restoring(Post $post)
{
// store to custom property
$post->temp_deleted_at = $post->deleted_at;
}
public function restored(Post $post)
{
// retrieve from custom property for query
$post->comments()
->onlyTrashed()->where('deleted_at', '>=', $post->temp_deleted_at)
->get()
->each(function ($comment) {
$comment->restore();
});
}
您应该能够使用$model->getOriginal('deleted_at')
在restored()
侦听器中检索deleted_at
的原始值。