<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think\model;
use Closure;
use ReflectionFunction;
use think\db\BaseQuery as Query;
use think\db\exception\DbException as Exception;
use think\Model;
abstract class Relation
{
protected $parent;
protected $model;
protected $query;
protected $foreignKey;
protected $localKey;
protected $baseQuery;
protected $selfRelation = false;
protected $withLimit;
protected $withField;
public function getParent(): Model
{
return $this->parent;
}
public function getQuery()
{
return $this->query;
}
public function getModel(): Model
{
return $this->query->getModel();
}
public function isSelfRelation(): bool
{
return $this->selfRelation;
}
protected function resultSetBuild(array $resultSet, Model $parent = null)
{
return (new $this->model)->toCollection($resultSet)->setParent($parent);
}
protected function getQueryFields(string $model)
{
$fields = $this->query->getOptions('field');
return $this->getRelationQueryFields($fields, $model);
}
protected function getRelationQueryFields($fields, string $model)
{
if (empty($fields) || '*' == $fields) {
return $model . '.*';
}
if (is_string($fields)) {
$fields = explode(',', $fields);
}
foreach ($fields as &$field) {
if (false === strpos($field, '.')) {
$field = $model . '.' . $field;
}
}
return $fields;
}
protected function getQueryWhere(array &$where, string $relation): void
{
foreach ($where as $key => &$val) {
if (is_string($key)) {
$where[] = [false === strpos($key, '.') ? $relation . '.' . $key : $key, '=', $val];
unset($where[$key]);
} elseif (isset($val[0]) && false === strpos($val[0], '.')) {
$val[0] = $relation . '.' . $val[0];
}
}
}
public function update(array $data = []): int
{
return $this->query->update($data);
}
public function delete($data = null): int
{
return $this->query->delete($data);
}
public function withLimit(int $limit)
{
$this->withLimit = $limit;
return $this;
}
public function withField(array $field)
{
$this->withField = $field;
return $this;
}
protected function getClosureType(Closure $closure)
{
$reflect = new ReflectionFunction($closure);
$params = $reflect->getParameters();
if (!empty($params)) {
$type = $params[0]->getType();
return is_null($type) || Relation::class == $type->getName() ? $this : $this->query;
}
return $this;
}
protected function baseQuery(): void
{}
public function __call($method, $args)
{
if ($this->query) {
$this->baseQuery();
$result = call_user_func_array([$this->query, $method], $args);
return $result === $this->query ? $this : $result;
}
throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
}
}