<?php<liu21st@gmail.com>
namespace think\model\relation;
use Closure;
use think\Collection;
use think\db\BaseQuery as Query;
use think\db\exception\DbException as Exception;
use think\db\Raw;
use think\Model;
use think\model\Pivot;
use think\model\Relation;
use think\Paginator;
class BelongsToMany extends Relation
{
protected $middle;
protected $pivotName;
protected $pivot;
protected $pivotDataName = 'pivot';
public function __construct(Model $parent, string $model, string $middle, string $foreignKey, string $localKey)
{
$this->parent = $parent;
$this->model = $model;
$this->foreignKey = $foreignKey;
$this->localKey = $localKey;
if (false !== strpos($middle, '\\')) {
$this->pivotName = $middle;
$this->middle = class_basename($middle);
} else {
$this->middle = $middle;
}
$this->query = (new $model)->db();
$this->pivot = $this->newPivot();
}
public function pivot(string $pivot)
{
$this->pivotName = $pivot;
return $this;
}
public function name(string $name)
{
$this->pivotDataName = $name;
return $this;
}
protected function newPivot(array $data = []): Pivot
{
$class = $this->pivotName ?: Pivot::class;
$pivot = new $class($data, $this->parent, $this->middle);
if ($pivot instanceof Pivot) {
return $pivot;
} else {
throw new Exception('pivot model must extends: \think\model\Pivot');
}
}
protected function hydratePivot(iterable $models)
{
foreach ($models as $model) {
$pivot = [];
foreach ($model->getData() as $key => $val) {
if (strpos($key, '__')) {
[$name, $attr] = explode('__', $key, 2);
if ('pivot' == $name) {
$pivot[$attr] = $val;
unset($model->$key);
}
}
}
$model->setRelation($this->pivotDataName, $this->newPivot($pivot));
}
}
public function getRelation(array $subRelation = [], Closure $closure = null): Collection
{
if ($closure) {
$closure($this->getClosureType($closure));
}
$result = $this->relation($subRelation)
->select()
->setParent(clone $this->parent);
$this->hydratePivot($result);
return $result;
}
public function select($data = null): Collection
{
$this->baseQuery();
$result = $this->query->select($data);
$this->hydratePivot($result);
return $result;
}
public function paginate($listRows = null, $simple = false): Paginator
{
$this->baseQuery();
$result = $this->query->paginate($listRows, $simple);
$this->hydratePivot($result);
return $result;
}
public function find($data = null)
{
$this->baseQuery();
$result = $this->query->find($data);
if ($result && !$result->isEmpty()) {
$this->hydratePivot([$result]);
}
return $result;
}
public function has(string $operator = '>=', $count = 1, $id = '*', string $joinType = 'INNER', Query $query = null)
{
return $this->parent;
}
public function hasWhere($where = [], $fields = null, string $joinType = '', Query $query = null)
{
throw new Exception('relation not support: hasWhere');
}
public function wherePivot($field, $op = null, $condition = null)
{
$this->query->where('pivot.' . $field, $op, $condition);
return $this;
}
public function eagerlyResultSet(array &$resultSet, string $relation, array $subRelation, Closure $closure = null, array $cache = []): void
{
$localKey = $this->localKey;
$pk = $resultSet[0]->getPk();
$range = [];
foreach ($resultSet as $result) {
if (isset($result->$pk)) {
$range[] = $result->$pk;
}
}
if (!empty($range)) {
$data = $this->eagerlyManyToMany([
['pivot.' . $localKey, 'in', $range],
], $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],
], $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],
])->$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()),
],
])->fetchSql()->$aggregate($field);
}
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;
}
protected function belongsToManyQuery(string $foreignKey, string $localKey, array $condition = []): Query
{
if (empty($this->baseQuery)) {
$tableName = $this->query->getTable();
$table = $this->pivot->db()->getTable();
$fields = $this->getQueryFields($tableName);
if ($this->withLimit) {
$this->query->limit($this->withLimit);
}
$this->query
->field($fields)
->tableField(true, $table, 'pivot', 'pivot__')
->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $this->query->getPk())
->where($condition);
}
return $this->query;
}
public function save($data, array $pivot = [])
{
return $this->attach($data, $pivot);
}
public function saveAll(iterable $dataSet, array $pivot = [], bool $samePivot = false)
{
$result = [];
foreach ($dataSet as $key => $data) {
if (!$samePivot) {
$pivotData = $pivot[$key] ?? [];
} else {
$pivotData = $pivot;
}
$result[] = $this->attach($data, $pivotData);
}
return empty($result) ? false : $result;
}
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);
}
} elseif (is_numeric($data) || is_string($data)) {
$id = $data;
} elseif ($data instanceof Model) {
$id = $data->getKey();
}
if (!empty($id)) {
$pivot[$this->localKey] = $this->parent->getKey();
$ids = (array) $id;
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->foreignKey, $id)
->find();
return $pivot ?: false;
}
public function detach($data = null, bool $relationDel = false): int
{
if (is_array($data)) {
$id = $data;
} elseif (is_numeric($data) || is_string($data)) {
$id = $data;
} elseif ($data instanceof Model) {
$id = $data->getKey();
}
$pivot = [];
$pivot[] = [$this->localKey, '=', $this->parent->getKey()];
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())
->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;
} elseif (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;
if (null === $this->parent->getKey()) {
$condition = ['pivot.' . $localKey, 'exp', new Raw('=' . $this->parent->getTable() . '.' . $this->parent->getPk())];
} else {
$condition = ['pivot.' . $localKey, '=', $this->parent->getKey()];
}
$this->belongsToManyQuery($foreignKey, $localKey, [$condition]);
$this->baseQuery = true;
}
}
}