<?php<448901948@qq.com>
namespace think\model;
use think\Collection as BaseCollection;
use think\Model;
class Collection extends BaseCollection
{
public function column($column_key, $index_key = null)
{
return array_column($this->toArray(), $column_key, $index_key);
}
public function load($relation)
{
$item = current($this->items);
$item->eagerlyResultSet($this->items, $relation);
return $this;
}
public function hidden($hidden = [], $override = false)
{
$this->each(function ($model) use ($hidden, $override) {
$model->hidden($hidden, $override);
});
return $this;
}
public function visible($visible = [], $override = false)
{
$this->each(function ($model) use ($visible, $override) {
$model->visible($visible, $override);
});
return $this;
}
public function append($append = [], $override = false)
{
$this->each(function ($model) use ($append, $override) {
$model && $model->append($append, $override);
});
return $this;
}
public function withAttr($name, $callback = null)
{
$this->each(function ($model) use ($name, $callback) {
$model && $model->withAttribute($name, $callback);
});
return $this;
}
public function dictionary($items = null)
{
$items = is_null($items) ? $this->items : $items;
if ($items) {
$indexKey = $items[0]->getPk();
}
if (isset($indexKey) && is_string($indexKey)) {
return array_column($items, null, $indexKey);
}
return $items;
}
public function diff($items)
{
$diff = [];
$dictionary = $this->dictionary($items);
foreach ($this->items as $item) {
if (!isset($dictionary[$item->getkey()])) {
$diff[] = $item;
}
}
return new static($diff);
}
public function intersect($items)
{
$intersect = [];
$dictionary = $this->dictionary($items);
foreach ($this->items as $item) {
if (isset($dictionary[$item->getkey()])) {
$intersect[] = $item;
}
}
return new static($intersect);
}
}