laravel5.5 Custom Collections功能提供扩展方法

场景

最近看到了一个有意思的功能

Once you have defined a newCollection method, you will receive an instance of your custom collection anytime Eloquent returns a Collection instance of that model. If you would like to use a custom collection for every model in your application, you should override the newCollection method on a base model class that is extended by all of your models.

在model里面定义public function ;那么单个的Model collection是可以访问的 ; 但是如果是get() 获取的多维的collection
是不可以调用的; Custom Collection这个功能就可以解决这个问题

具体的应用场景

在开发私信组件的时候,如果用户进入了私信对话列表组件 那么在Vue mounted的时候 发送两个请求

私信列表
标记未读私信为已读

关于标记已读也是发送了一个请求去执行sql update; 当然是可以在第一请求的时候直接执行的;哈哈 下面用的地方来了 这时候一般是array_walk遍历update; 但是现在多了一个选择(其实也只是做的更规范一些;本质上没有变化 ) 具体的解决方案见下面

分析

  • Custom Collection功能对Model function的扩展; 它使collects也可以向collect那样调用函数(个人理解)

参考文章

https://laravel.com/docs/5.6/eloquent-collections#custom-collections

解决

  • 私信Model中定义一个将单条私信标记为已读的方法markAsRead
  • 定制 newCollection方法 这个基本上是固定的
  • 在定制的扩展的Collection中定义markAsRead方法循环调用私信Model的方法markAsRead
    当然可以不复写markAsRead,另外选个名字,但是官方文档说的很正点:override可以让你无论是collect 还是 collects都可以使用markAsRead
class MessageCollection extends Collection
{
    public function markAsRead()
    {
        $this->each(function($model){
            $model->markAsRead();
        });
    }
}
    /**
     * 将未阅读的私信标记为已阅读
     */
    public function  markAsRead()
    {
        if ($this->is_read === 'F') {
            $is_read = 'T';
            $read_at = now();
            $this->fill(compact('is_read', 'read_at'))->save();
        }
    }

    public function newCollection(array $models = [])
    {
        return new MessageCollection($models);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值