<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think\db\concern;
use Closure;
use think\helper\Str;
use think\Model;
use think\model\Collection as ModelCollection;
trait ModelRelationQuery
{
protected $model;
public function model(Model $model)
{
$this->model = $model;
return $this;
}
public function getModel()
{
return $this->model;
}
public function hidden(array $hidden)
{
$this->options['hidden'] = $hidden;
return $this;
}
public function visible(array $visible)
{
$this->options['visible'] = $visible;
return $this;
}
public function append(array $append)
{
$this->options['append'] = $append;
return $this;
}
public function scope($scope, ...$args)
{
array_unshift($args, $this);
if ($scope instanceof Closure) {
call_user_func_array($scope, $args);
return $this;
}
if (is_string($scope)) {
$scope = explode(',', $scope);
}
if ($this->model) {
foreach ($scope as $name) {
$method = 'scope' . trim($name);
if (method_exists($this->model, $method)) {
call_user_func_array([$this->model, $method], $args);
}
}
}
return $this;
}
public function relation(array $relation)
{
if (!empty($relation)) {
$this->options['relation'] = $relation;
}
return $this;
}
public function withSearch($fields, $data = [], string $prefix = '')
{
if (is_string($fields)) {
$fields = explode(',', $fields);
}
$likeFields = $this->getConfig('match_like_fields') ?: [];
foreach ($fields as $key => $field) {
if ($field instanceof Closure) {
$field($this, $data[$key] ?? null, $data, $prefix);
} elseif ($this->model) {
$fieldName = is_numeric($key) ? $field : $key;
$method = 'search' . Str::studly($fieldName) . 'Attr';
if (method_exists($this->model, $method)) {
$this->model->$method($this, $data[$field] ?? null, $data, $prefix);
} elseif (isset($data[$field])) {
$this->where($fieldName, in_array($fieldName, $likeFields) ? 'like' : '=', in_array($fieldName, $likeFields) ? '%' . $data[$field] . '%' : $data[$field]);
}
}
}
return $this;
}
public function withAttr($name, callable $callback = null)
{
if (is_array($name)) {
$this->options['with_attr'] = $name;
} else {
$this->options['with_attr'][$name] = $callback;
}
return $this;
}
public function with($with)
{
if (!empty($with)) {
$this->options['with'] = (array) $with;
}
return $this;
}
public function withJoin($with, string $joinType = '')
{
if (empty($with)) {
return $this;
}
$with = (array) $with;
$first = true;
foreach ($with as $key => $relation) {
$closure = null;
$field = true;
if ($relation instanceof Closure) {
$closure = $relation;
$relation = $key;
} elseif (is_array($relation)) {
$field = $relation;
$relation = $key;
} elseif (is_string($relation) && strpos($relation, '.')) {
$relation = strstr($relation, '.', true);
}
$result = $this->model->eagerly($this, $relation, $field, $joinType, $closure, $first);
if (!$result) {
unset($with[$key]);
} else {
$first = false;
}
}
$this->via();
$this->options['with_join'] = $with;
return $this;
}
protected function withAggregate($relations, string $aggregate = 'count', $field = '*', bool $subQuery = true)
{
if (!$subQuery) {
$this->options['with_count'][] = [$relations, $aggregate, $field];
} else {
if (!isset($this->options['field'])) {
$this->field('*');
}
$this->model->relationCount($this, (array) $relations, $aggregate, $field, true);
}
return $this;
}
public function withCache($relation = true, $key = true, $expire = null, string $tag = null)
{
if (false === $relation || false === $key || !$this->getConnection()->getCache()) {
return $this;
}
if ($key instanceof \DateTimeInterface || $key instanceof \DateInterval || (is_int($key) && is_null($expire))) {
$expire = $key;
$key = true;
}
if (true === $relation || is_numeric($relation)) {
$this->options['with_cache'] = $relation;
return $this;
}
$relations = (array) $relation;
foreach ($relations as $name => $relation) {
if (!is_numeric($name)) {
$this->options['with_cache'][$name] = is_array($relation) ? $relation : [$key, $relation, $tag];
} else {
$this->options['with_cache'][$relation] = [$key, $expire, $tag];
}
}
return $this;
}
public function withCount($relation, bool $subQuery = true)
{
return $this->withAggregate($relation, 'count', '*', $subQuery);
}
public function withSum($relation, string $field, bool $subQuery = true)
{
return $this->withAggregate($relation, 'sum', $field, $subQuery);
}
public function withMax($relation, string $field, bool $subQuery = true)
{
return $this->withAggregate($relation, 'max', $field, $subQuery);
}
public function withMin($relation, string $field, bool $subQuery = true)
{
return $this->withAggregate($relation, 'min', $field, $subQuery);
}
public function withAvg($relation, string $field, bool $subQuery = true)
{
return $this->withAggregate($relation, 'avg', $field, $subQuery);
}
public function has(string $relation, string $operator = '>=', int $count = 1, string $id = '*', string $joinType = '')
{
return $this->model->has($relation, $operator, $count, $id, $joinType, $this);
}
public function hasWhere(string $relation, $where = [], string $fields = '*', string $joinType = '')
{
return $this->model->hasWhere($relation, $where, $fields, $joinType, $this);
}
protected function resultSetToModelCollection(array $resultSet): ModelCollection
{
if (empty($resultSet)) {
return $this->model->toCollection();
}
if (!empty($this->options['with_attr'])) {
foreach ($this->options['with_attr'] as $name => $val) {
if (strpos($name, '.')) {
[$relation, $field] = explode('.', $name);
$withRelationAttr[$relation][$field] = $val;
unset($this->options['with_attr'][$name]);
}
}
}
$withRelationAttr = $withRelationAttr ?? [];
foreach ($resultSet as $key => &$result) {
$this->resultToModel($result, $this->options, true, $withRelationAttr);
}
if (!empty($this->options['with'])) {
$result->eagerlyResultSet($resultSet, $this->options['with'], $withRelationAttr, false, $this->options['with_cache'] ?? false);
}
if (!empty($this->options['with_join'])) {
$result->eagerlyResultSet($resultSet, $this->options['with_join'], $withRelationAttr, true, $this->options['with_cache'] ?? false);
}
return $this->model->toCollection($resultSet);
}
protected function resultToModel(array &$result, array $options = [], bool $resultSet = false, array $withRelationAttr = []): void
{
if (!empty($options['with_attr']) && empty($withRelationAttr)) {
foreach ($options['with_attr'] as $name => $val) {
if (strpos($name, '.')) {
[$relation, $field] = explode('.', $name);
$withRelationAttr[$relation][$field] = $val;
unset($options['with_attr'][$name]);
}
}
}
if (!empty($options['json'])) {
$this->jsonResult($result, $options['json'], $options['json_assoc'], $withRelationAttr);
}
$result = $this->model
->newInstance($result, $resultSet ? null : $this->getModelUpdateCondition($options));
if (!empty($options['with_attr'])) {
$result->withAttribute($options['with_attr']);
}
if (!empty($options['visible'])) {
$result->visible($options['visible']);
} elseif (!empty($options['hidden'])) {
$result->hidden($options['hidden']);
}
if (!empty($options['append'])) {
$result->append($options['append']);
}
if (!empty($options['relation'])) {
$result->relationQuery($options['relation'], $withRelationAttr);
}
if (!$resultSet && !empty($options['with'])) {
$result->eagerlyResult($result, $options['with'], $withRelationAttr, false, $options['with_cache'] ?? false);
}
if (!$resultSet && !empty($options['with_join'])) {
$result->eagerlyResult($result, $options['with_join'], $withRelationAttr, true, $options['with_cache'] ?? false);
}
if (!empty($options['with_count'])) {
foreach ($options['with_count'] as $val) {
$result->relationCount($this, (array) $val[0], $val[1], $val[2], false);
}
}
}
}