0

我只是想知道如何为数据透视表中的属性实现 Presenter 模式?例如,考虑这段代码(它只是一个例子,不是我实际代码的复制):

@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

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

非常感谢任何帮助

谢谢!

4

2 回答 2

1

您可以覆盖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);
}

CommentUserPivot 模型

class CommentUserPivot extends \Illuminate\Database\Eloquent\Relations\Pivot {
    // presenter stuff
}
于 2015-01-15T15:21:20.693 回答
0

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

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

于 2015-01-15T15:00:57.230 回答