<?php<448901948@qq.com>declare (strict_types = 1);
namespace think\model;
use think\Collection as BaseCollection;
use think\Model;
use think\Paginator;
class Collection extends BaseCollection
{
public function load($relation, $cache = false)
{
if (!$this->isEmpty()) {
$item = current($this->items);
$item->eagerlyResultSet($this->items, (array) $relation, [], false, $cache);
}
return $this;
}
public function delete(): bool
{
$this->each(function (Model $model) {
$model->delete();
});
return true;
}
public function update(array $data, array $allowField = []): bool
{
$this->each(function (Model $model) use ($data, $allowField) {
if (!empty($allowField)) {
$model->allowField($allowField);
}
$model->save($data);
});
return true;
}
public function hidden(array $hidden)
{
$this->each(function (Model $model) use ($hidden) {
$model->hidden($hidden);
});
return $this;
}
public function visible(array $visible)
{
$this->each(function (Model $model) use ($visible) {
$model->visible($visible);
});
return $this;
}
public function append(array $append)
{
$this->each(function (Model $model) use ($append) {
$model->append($append);
});
return $this;
}
public function scene(string $scene)
{
$this->each(function (Model $model) use ($scene) {
$model->scene($scene);
});
return $this;
}
public function setParent(Model $parent)
{
$this->each(function (Model $model) use ($parent) {
$model->setParent($parent);
});
return $this;
}
public function withAttr($name, $callback = null)
{
$this->each(function (Model $model) use ($name, $callback) {
$model->withAttribute($name, $callback);
});
return $this;
}
public function bindAttr(string $relation, array $attrs = [])
{
$this->each(function (Model $model) use ($relation, $attrs) {
$model->bindAttr($relation, $attrs);
});
return $this;
}
public function dictionary($items = null, string &$indexKey = null)
{
if ($items instanceof self || $items instanceof Paginator) {
$items = $items->all();
}
$items = is_null($items) ? $this->items : $items;
if ($items && empty($indexKey)) {
$indexKey = $items[0]->getPk();
}
if (isset($indexKey) && is_string($indexKey)) {
return array_column($items, null, $indexKey);
}
return $items;
}
public function diff($items, string $indexKey = null)
{
if ($this->isEmpty()) {
return new static($items);
}
$diff = [];
$dictionary = $this->dictionary($items, $indexKey);
if (is_string($indexKey)) {
foreach ($this->items as $item) {
if (!isset($dictionary[$item[$indexKey]])) {
$diff[] = $item;
}
}
}
return new static($diff);
}
public function intersect($items, string $indexKey = null)
{
if ($this->isEmpty()) {
return new static([]);
}
$intersect = [];
$dictionary = $this->dictionary($items, $indexKey);
if (is_string($indexKey)) {
foreach ($this->items as $item) {
if (isset($dictionary[$item[$indexKey]])) {
$intersect[] = $item;
}
}
}
return new static($intersect);
}
}