chengkun
2025-06-05 4080b5997b38ca84b3b203c7101dcadb97b76925
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<?php
 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <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
{
    /**
     * 多态关系的模型名映射别名的数组.
     *
     * @var array
     */
    protected static $morphMap = [];
 
    /**
     * 多态字段名.
     *
     * @var string
     */
    protected $morphType;
 
    /**
     * 多态模型名.
     *
     * @var string
     */
    protected $morphClass;
 
    /**
     * 是否反向关联.
     *
     * @var bool
     */
    protected $inverse;
 
    /**
     * 架构函数.
     *
     * @param Model  $parent    上级模型对象
     * @param string $model     模型名
     * @param string $middle    中间表名/模型名
     * @param string $morphKey  关联外键
     * @param string $morphType 多态字段名
     * @param string $localKey  当前模型关联键
     * @param bool   $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);
 
        if (isset(static::$morphMap[$this->morphClass])) {
            $this->morphClass = static::$morphMap[$this->morphClass];
        }
 
        $foreignKey = $inverse ? $morphKey : $localKey;
        $localKey   = $inverse ? $localKey : $morphKey;
 
        parent::__construct($parent, $model, $middle, $foreignKey, $localKey);
    }
 
    /**
     * 预载入关联查询(数据集).
     *
     * @param array   $resultSet   数据集
     * @param string  $relation    当前关联名
     * @param array   $subRelation 子关联名
     * @param Closure $closure     闭包
     * @param array   $cache       关联缓存
     *
     * @return void
     */
    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));
            }
        }
    }
 
    /**
     * 预载入关联查询(单个数据).
     *
     * @param Model   $result      数据对象
     * @param string  $relation    当前关联名
     * @param array   $subRelation 子关联名
     * @param Closure $closure     闭包
     * @param array   $cache       关联缓存
     *
     * @return void
     */
    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));
        }
    }
 
    /**
     * 关联统计
     *
     * @param Model   $result    数据对象
     * @param Closure $closure   闭包
     * @param string  $aggregate 聚合查询方法
     * @param string  $field     字段
     * @param string  $name      统计字段别名
     *
     * @return int
     */
    public function relationCount(Model $result, ?Closure $closure = null, string $aggregate = 'count', string $field = '*', ?string &$name = null)
    {
        $pk = $result->getPk();
 
        if (!isset($result->$pk)) {
            return 0;
        }
 
        if ($closure) {
            $closure($this->query, $name);
        }
 
        return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
            ['pivot.' . $this->localKey, '=', $result->$pk],
            ['pivot.' . $this->morphType, '=', $this->morphClass],
        ])->$aggregate($field);
    }
 
    /**
     * 获取关联统计子查询.
     *
     * @param Closure $closure   闭包
     * @param string  $aggregate 聚合查询方法
     * @param string  $field     字段
     * @param string  $name      统计字段别名
     *
     * @return string
     */
    public function getRelationCountQuery(?Closure $closure = null, string $aggregate = 'count', string $field = '*', ?string &$name = null): string
    {
        if ($closure) {
            $closure($this->query, $name);
        }
 
        return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
            ['pivot.' . $this->localKey, 'exp', new Raw('=' . $this->parent->db(false)->getTable(true) . '.' . $this->parent->getPk())],
            ['pivot.' . $this->morphType, '=', $this->morphClass],
        ])->fetchSql()->$aggregate($field);
    }
 
    /**
     * BELONGS TO MANY 关联查询.
     *
     * @param string $foreignKey 关联模型关联键
     * @param string $localKey   当前模型关联键
     * @param array  $condition  关联查询条件
     *
     * @return Query
     */
    protected function belongsToManyQuery(string $foreignKey, string $localKey, array $condition = []): Query
    {
        // 关联查询封装
        $tableName  = $this->query->getTable();
        $table      = $this->pivot->db()->getTable();
        $fields     = $this->getQueryFields($tableName);
 
        $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;
    }
 
    /**
     * 多对多 关联模型预查询.
     *
     * @param array   $where       关联预查询条件
     * @param array   $subRelation 子关联
     * @param Closure $closure     闭包
     * @param array   $cache       关联缓存
     *
     * @return array
     */
    protected function eagerlyManyToMany(array $where, array $subRelation = [], ?Closure $closure = null, array $cache = []): array
    {
        if ($closure) {
            $closure($this->query);
        }
 
        $withLimit = $this->query->getOptions('limit');
        if ($withLimit) {
            $this->query->removeOption('limit');
        }
 
        // 预载入关联查询 支持嵌套预载入
        $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 (str_contains($key, '__')) {
                    [$name, $attr] = explode('__', $key, 2);
                    if ('pivot' == $name) {
                        $pivot[$attr] = $val;
                        unset($set->$key);
                    }
                }
            }
 
            $key = $pivot[$this->localKey];
 
            if ($withLimit && isset($data[$key]) && count($data[$key]) >= $withLimit) {
                continue;
            }
 
            $set->setRelation($this->pivotDataName, $this->newPivot($pivot));
 
            $data[$key][] = $set;
        }
 
        return $data;
    }
 
    /**
     * 附加关联的一个中间表数据.
     *
     * @param mixed $data  数据 可以使用数组、关联模型对象 或者 关联对象的主键
     * @param array $pivot 中间表额外数据
     *
     * @return array|Pivot
     */
    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();
            $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');
        }
    }
 
    /**
     * 判断是否存在关联数据.
     *
     * @param mixed $data 数据 可以使用关联模型对象 或者 关联对象的主键
     *
     * @return Pivot|false
     */
    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;
    }
 
    /**
     * 解除关联的一个中间表数据.
     *
     * @param int|array $data        数据 可以使用关联对象的主键
     * @param bool      $relationDel 是否同时删除关联表数据
     *
     * @return int
     */
    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 = [
            [$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;
    }
 
    /**
     * 数据同步.
     *
     * @param array $ids
     * @param bool  $detaching
     *
     * @return array
     */
    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;
            } elseif (count($attributes) > 0 && $this->attach($id, $attributes)) {
                $changes['updated'][] = $id;
            }
        }
 
        return $changes;
    }
 
    /**
     * 执行基础查询(仅执行一次).
     *
     * @return void
     */
    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;
        }
    }
 
    /**
     * 设置或获取多态关系的模型名映射别名的数组.
     *
     * @param array|null $map
     * @param bool       $merge
     *
     * @return array
     */
    public static function morphMap(?array $map = null, $merge = true): array
    {
        if (is_array($map)) {
            static::$morphMap = $merge && static::$morphMap
                ? $map + static::$morphMap : $map;
        }
 
        return static::$morphMap;
    }
}