【问题标题】:Using a presenter on attributes in a pivot table in Laravel在 Laravel 的数据透视表中对属性使用演示者
【发布时间】:2015-03-14 00:03:56
【问题描述】:

我只是想知道如何为数据透视表中的属性实现 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

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

非常感谢任何帮助

谢谢!

【问题讨论】:

    标签: php design-patterns laravel eloquent presenter


    【解决方案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
    }
    

    【讨论】:

    • 我似乎无法正常工作。我在两个表上都使用了 ->belongsToMany 关系,我不知道这是否有什么不同?似乎它从未调用过'newPivot'
    • 您是否在两个模型中都添加了newPivot?使用$user-&gt;commentsnewPivot会在Comment模型中调用
    • 没关系它工作正常,谢谢!我的问题是我使用的自动演示器包似乎没有装饰 Pivot
    • 好的。不幸的是,我无法帮助你。从来没用过这个包。祝你好运!
    【解决方案2】:

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

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

    【讨论】:

    • 我正在使用这个确切的包,我想知道如何呈现“枢轴”属性,而不仅仅是我正在呈现的模型上的那些(例如,将在users_comments 表在我的示例中,与 users 表相反)
    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 2017-10-18
    • 2018-08-18
    • 2021-01-09
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2015-01-10
    相关资源
    最近更新 更多