在 Laravel 中对数据透视表中的属性使用演示器


Using a presenter on attributes in a pivot table in Laravel

我只是想知道如何为数据透视表内的属性实现演示器模式?例如,考虑以下代码(它只是一个示例,不是我实际代码的复制):

@foreach($users->comments as $comment)
 <h1>{{ $comment->title }}</h1> // calls 'title()' in CommentPresenter
 <p>{{ $comment->body }}</p> // calls 'body()' in CommentPresenter...
 <p>{{ is_null($comment->pivot->deleted_at) ? '' : '[REMOVED]' :}} // Where can I put this???
@endforeach

我可以在哪里放置最终属性呈现方法?请记住,我也希望能够使用这种关系的反转。

任何帮助非常感谢

谢谢!

您可以在模型中覆盖newPivot,然后使用自己的Pivot模型。它将主要被视为"普通"Eloquent 模型,因此自动演示器包应该可以工作。

注释模型

public function newPivot(Model $parent, array $attributes, $table, $exists)
{
    if($parent instanceof User){
        return new CommentUserPivot($parent, $attributes, $table, $exists);
    }
    return parent::newPivot($parent, $attributes, $table, $exists);
}

用户模型

public function newPivot(Model $parent, array $attributes, $table, $exists)
{
    if($parent instanceof Comment){
        return new CommentUserPivot($parent, $attributes, $table, $exists);
    }
    return parent::newPivot($parent, $attributes, $table, $exists);
}

注释用户透视模型

class CommentUserPivot extends 'Illuminate'Database'Eloquent'Relations'Pivot {
    // presenter stuff
}

您可以使用Laravel自动呈现包。它将允许您使用特定方法在模型上实现表示器类,以覆盖模型的正常数据属性。但是,我不相信这会在进入模型的过程中格式化数据(如果这就是你所说的逆向)。

https://github.com/ShawnMcCool/laravel-auto-presenter