场景
最近看到了一个有意思的功能
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);
}