Collection.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: zhangyajun <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\model;
  12. use think\Collection as BaseCollection;
  13. use think\Model;
  14. class Collection extends BaseCollection
  15. {
  16. /**
  17. * 延迟预载入关联查询
  18. * @access public
  19. * @param mixed $relation 关联
  20. * @return $this
  21. */
  22. public function load($relation)
  23. {
  24. if (!$this->isEmpty()) {
  25. $item = current($this->items);
  26. $item->eagerlyResultSet($this->items, $relation);
  27. }
  28. return $this;
  29. }
  30. /**
  31. * 设置需要隐藏的输出属性
  32. * @access public
  33. * @param array $hidden 属性列表
  34. * @param bool $override 是否覆盖
  35. * @return $this
  36. */
  37. public function hidden($hidden = [], $override = false)
  38. {
  39. $this->each(function ($model) use ($hidden, $override) {
  40. /** @var Model $model */
  41. $model->hidden($hidden, $override);
  42. });
  43. return $this;
  44. }
  45. /**
  46. * 设置需要输出的属性
  47. * @access public
  48. * @param array $visible
  49. * @param bool $override 是否覆盖
  50. * @return $this
  51. */
  52. public function visible($visible = [], $override = false)
  53. {
  54. $this->each(function ($model) use ($visible, $override) {
  55. /** @var Model $model */
  56. $model->visible($visible, $override);
  57. });
  58. return $this;
  59. }
  60. /**
  61. * 设置需要追加的输出属性
  62. * @access public
  63. * @param array $append 属性列表
  64. * @param bool $override 是否覆盖
  65. * @return $this
  66. */
  67. public function append($append = [], $override = false)
  68. {
  69. $this->each(function ($model) use ($append, $override) {
  70. /** @var Model $model */
  71. $model && $model->append($append, $override);
  72. });
  73. return $this;
  74. }
  75. /**
  76. * 设置数据字段获取器
  77. * @access public
  78. * @param string|array $name 字段名
  79. * @param callable $callback 闭包获取器
  80. * @return $this
  81. */
  82. public function withAttr($name, $callback = null)
  83. {
  84. $this->each(function ($model) use ($name, $callback) {
  85. /** @var Model $model */
  86. $model && $model->withAttribute($name, $callback);
  87. });
  88. return $this;
  89. }
  90. }