<?php<liu21st@gmail.com>
namespace think\model\relation;
use Closure;
use Exception;
use think\db\BaseQuery as Query;
use think\db\Raw;
use think\Model;
use think\model\Pivot;
class MorphToMany extends BelongsToMany
{
protected $morphType;
protected $morphClass;
protected $inverse;
public function __construct(Model $parent, string $model, string $middle, string $morphType, string $morphKey, string $localKey, bool $inverse = false)
{
$this->morphType = $morphType;
$this->inverse = $inverse;
$this->morphClass = $inverse ? $model : get_class($parent);
$foreignKey = $inverse ? $morphKey : $localKey;
$localKey = $inverse ? $localKey : $morphKey;
parent::__construct($parent, $model, $middle, $foreignKey, $localKey);
}
public function eagerlyResultSet(array &$resultSet, string $relation, array $subRelation, Closure $closure = null, array $cache = []): void
{
$pk = $resultSet[0]->getPk();
$range = [];
foreach ($resultSet as $result) {
if (isset($result->$pk)) {
$range[] = $result->$pk;
}
}
if (!empty($range)) {
$data = $this->eagerlyManyToMany([
['pivot.' . $this->localKey, 'in', $range],
['pivot.' . $this->morphType, '=', $this->morphClass],
], $subRelation, $closure, $cache);
foreach ($resultSet as $result) {
if (!isset($data[$result->$pk])) {
$data[$result->$pk] = [];
}
$result->setRelation($relation, $this->resultSetBuild($data[$result->$pk], clone $this->parent));
}
}
}
public function eagerlyResult(Model $result, string $relation, array $subRelation, Closure $closure = null, array $cache = []): void
{
$pk = $result->getPk();
if (isset($result->$pk)) {
$pk = $result->$pk;
$data = $this->eagerlyManyToMany([
['pivot.' . $this->localKey, '=', $pk],
['pivot.' . $this->morphType, '=', $this->morphClass],
], $subRelation, $closure, $cache);
if (!isset($data[$pk])) {
$data[$pk] = [];
}
$result->setRelation($relation, $this->resultSetBuild($data[$pk], clone $this->parent));
}
}
public function relationCount(Model $result, Closure $closure = null, string $aggregate = 'count', string $field = '*', string &$name = null): float
{
$pk = $result->getPk();
if (!isset($result->$pk)) {
return 0;
}
$pk = $result->$pk;
if ($closure) {
$closure($this->getClosureType($closure), $name);
}
return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
['pivot.' . $this->localKey, '=', $pk],
['pivot.' . $this->morphType, '=', $this->morphClass],
])->$aggregate($field);
}
public function getRelationCountQuery(Closure $closure = null, string $aggregate = 'count', string $field = '*', string &$name = null): string
{
if ($closure) {
$closure($this->getClosureType($closure), $name);
}
return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
['pivot.' . $this->localKey, 'exp', new Raw('=' . $this->parent->db(false)->getTable() . '.' . $this->parent->getPk())],
['pivot.' . $this->morphType, '=', $this->morphClass],
])->fetchSql()->$aggregate($field);
}
protected function belongsToManyQuery(string $foreignKey, string $localKey, array $condition = []): Query
{
$tableName = $this->query->getTable();
$table = $this->pivot->db()->getTable();
$fields = $this->getQueryFields($tableName);
if ($this->withLimit) {
$this->query->limit($this->withLimit);
}
$query = $this->query
->field($fields)
->tableField(true, $table, 'pivot', 'pivot__');
if (empty($this->baseQuery)) {
$relationFk = $this->query->getPk();
$query->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk)
->where($condition);
}
return $query;
}
protected function eagerlyManyToMany(array $where, array $subRelation = [], Closure $closure = null, array $cache = []): array
{
if ($closure) {
$closure($this->getClosureType($closure));
}
$list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where)
->with($subRelation)
->cache($cache[0] ?? false, $cache[1] ?? null, $cache[2] ?? null)
->select();
$data = [];
foreach ($list as $set) {
$pivot = [];
foreach ($set->getData() as $key => $val) {
if (strpos($key, '__')) {
[$name, $attr] = explode('__', $key, 2);
if ('pivot' == $name) {
$pivot[$attr] = $val;
unset($set->$key);
}
}
}
$key = $pivot[$this->localKey];
if ($this->withLimit && isset($data[$key]) && count($data[$key]) >= $this->withLimit) {
continue;
}
$set->setRelation($this->pivotDataName, $this->newPivot($pivot));
$data[$key][] = $set;
}
return $data;
}
public function attach($data, array $pivot = [])
{
if (is_array($data)) {
if (key($data) === 0) {
$id = $data;
} else {
$model = new $this->model;
$id = $model->insertGetId($data);
}
} else if (is_numeric($data) || is_string($data)) {
$id = $data;
} else if ($data instanceof Model) {
$id = $data->getKey();
}
if (!empty($id)) {
$pivot[$this->localKey] = $this->parent->getKey();
$pivot[$this->morphType] = $this->morphClass;
$ids = (array) $id;
$result = [];
foreach ($ids as $id) {
$pivot[$this->foreignKey] = $id;
$this->pivot->replace()
->exists(false)
->data([])
->save($pivot);
$result[] = $this->newPivot($pivot);
}
if (count($result) == 1) {
$result = $result[0];
}
return $result;
} else {
throw new Exception('miss relation data');
}
}
public function attached($data)
{
if ($data instanceof Model) {
$id = $data->getKey();
} else {
$id = $data;
}
$pivot = $this->pivot
->where($this->localKey, $this->parent->getKey())
->where($this->morphType, $this->morphClass)
->where($this->foreignKey, $id)
->find();
return $pivot ?: false;
}
public function detach($data = null, bool $relationDel = false): int
{
if (is_array($data)) {
$id = $data;
} else if (is_numeric($data) || is_string($data)) {
$id = $data;
} else if ($data instanceof Model) {
$id = $data->getKey();
}
$pivot = [
[$this->localKey, '=', $this->parent->getKey()],
[$this->morphType, '=', $this->morphClass],
];
if (isset($id)) {
$pivot[] = [$this->foreignKey, is_array($id) ? 'in' : '=', $id];
}
$result = $this->pivot->where($pivot)->delete();
if (isset($id) && $relationDel) {
$model = $this->model;
$model::destroy($id);
}
return $result;
}
public function sync(array $ids, bool $detaching = true): array
{
$changes = [
'attached' => [],
'detached' => [],
'updated' => [],
];
$current = $this->pivot
->where($this->localKey, $this->parent->getKey())
->where($this->morphType, $this->morphClass)
->column($this->foreignKey);
$records = [];
foreach ($ids as $key => $value) {
if (!is_array($value)) {
$records[$value] = [];
} else {
$records[$key] = $value;
}
}
$detach = array_diff($current, array_keys($records));
if ($detaching && count($detach) > 0) {
$this->detach($detach);
$changes['detached'] = $detach;
}
foreach ($records as $id => $attributes) {
if (!in_array($id, $current)) {
$this->attach($id, $attributes);
$changes['attached'][] = $id;
} else if (count($attributes) > 0 && $this->attach($id, $attributes)) {
$changes['updated'][] = $id;
}
}
return $changes;
}
protected function baseQuery(): void
{
if (empty($this->baseQuery)) {
$foreignKey = $this->foreignKey;
$localKey = $this->localKey;
$this->belongsToManyQuery($foreignKey, $localKey, [
['pivot.' . $localKey, '=', $this->parent->getKey()],
['pivot.' . $this->morphType, '=', $this->morphClass],
]);
$this->baseQuery = true;
}
}
}