Blogger Information
Blog 47
fans 1
comment 0
visits 53023
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
laravel 自定义方法 - 数据库返回纯数组
晴天
Original
1345 people have browsed it

扩展集合

集合都是「可宏扩展」(macroable) 的,它允许你在执行时将其它方法添加到 Collection 类。例如,通过下面的代码在 Collection 类中添加一个 toUpper 方法:

  1. use Illuminate\Support\Collection;
  2. use Illuminate\Support\Str;
  3. Collection::macro('toUpper', function () {
  4. return $this->map(function ($value) {
  5. return Str::upper($value);
  6. });
  7. });
  8. $collection = collect(['first', 'second']);
  9. $upper = $collection->toUpper();
  10. // ['FIRST', 'SECOND']
  • 我们要把我们的扩展写到 app/providers中创建新文件
    或者直接使用命令行
    1. php artisan make:provider DBServiceProvider
    use一下db类 QueryBulider
    将扩展写到boot方法中
  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\ServiceProvider;
  4. use Illuminate\Database\Query\Builder as QueryBuilder;
  5. class DBServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register services.
  9. *
  10. * @return void
  11. */
  12. public function register()
  13. {
  14. //
  15. }
  16. /**
  17. * Bootstrap services.
  18. *
  19. * @return void
  20. */
  21. public function boot()
  22. {
  23. QueryBuilder::macro('lists',function(){
  24. $data = $this->get()->toArray();
  25. $res = [];
  26. foreach ($data as $val) {
  27. $res[] = (array)$val;
  28. }
  29. return $res;
  30. });
  31. }
  32. }

然后需要去注册一下
打开 config/app.php文件 找到providers
在最后面添加一条

  1. // 扩展DBServiceProvider
  2. App\Providers\DBServiceProvider::class,

这样就可以正常调用了

关于扩展需要注意的地方

    1. 保证该类是可宏扩展的 至少use了Macroable
    1. 然后创建扩展 并把扩展的方法写到boot方法中
    1. 注册该方法
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post