|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace MongoDB\Laravel\Relations; |
| 6 | + |
| 7 | +use Illuminate\Database\Eloquent\Builder; |
| 8 | +use Illuminate\Database\Eloquent\Collection; |
| 9 | +use Illuminate\Database\Eloquent\Model; |
| 10 | +use Illuminate\Database\Eloquent\Relations\MorphToMany as EloquentMorphToMany; |
| 11 | +use Illuminate\Support\Arr; |
| 12 | + |
| 13 | +use function array_diff; |
| 14 | +use function array_key_exists; |
| 15 | +use function array_keys; |
| 16 | +use function array_map; |
| 17 | +use function array_merge; |
| 18 | +use function array_reduce; |
| 19 | +use function array_values; |
| 20 | +use function count; |
| 21 | +use function is_array; |
| 22 | +use function is_numeric; |
| 23 | + |
| 24 | +class MorphToMany extends EloquentMorphToMany |
| 25 | +{ |
| 26 | + /** @inheritdoc */ |
| 27 | + public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) |
| 28 | + { |
| 29 | + return $query; |
| 30 | + } |
| 31 | + |
| 32 | + /** @inheritdoc */ |
| 33 | + protected function hydratePivotRelation(array $models) |
| 34 | + { |
| 35 | + // Do nothing. |
| 36 | + } |
| 37 | + |
| 38 | + /** @inheritdoc */ |
| 39 | + protected function shouldSelect(array $columns = ['*']) |
| 40 | + { |
| 41 | + return $columns; |
| 42 | + } |
| 43 | + |
| 44 | + /** @inheritdoc */ |
| 45 | + public function addConstraints() |
| 46 | + { |
| 47 | + if (static::$constraints) { |
| 48 | + $this->setWhere(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + /** @inheritdoc */ |
| 53 | + public function addEagerConstraints(array $models) |
| 54 | + { |
| 55 | + // To load relation's data, we act normally on MorphToMany relation, |
| 56 | + // But on MorphedByMany relation, we collect related ids from pivot column |
| 57 | + // and add to a whereIn condition |
| 58 | + if ($this->getInverse()) { |
| 59 | + $ids = $this->getKeys($models, $this->table); |
| 60 | + $ids = $this->extractIds($ids[0] ?? []); |
| 61 | + $this->query->whereIn($this->relatedKey, $ids); |
| 62 | + } else { |
| 63 | + parent::addEagerConstraints($models); |
| 64 | + |
| 65 | + $this->query->where($this->qualifyPivotColumn($this->morphType), $this->morphClass); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Set the where clause for the relation query. |
| 71 | + * |
| 72 | + * @return $this |
| 73 | + */ |
| 74 | + protected function setWhere() |
| 75 | + { |
| 76 | + if ($this->getInverse()) { |
| 77 | + $ids = $this->extractIds((array) $this->parent->{$this->table}); |
| 78 | + |
| 79 | + $this->query->whereIn($this->relatedKey, $ids); |
| 80 | + } else { |
| 81 | + $this->query->whereIn($this->relatedKey, (array) $this->parent->{$this->relatedPivotKey}); |
| 82 | + } |
| 83 | + |
| 84 | + return $this; |
| 85 | + } |
| 86 | + |
| 87 | + /** @inheritdoc */ |
| 88 | + public function save(Model $model, array $joining = [], $touch = true) |
| 89 | + { |
| 90 | + $model->save(['touch' => false]); |
| 91 | + |
| 92 | + $this->attach($model, $joining, $touch); |
| 93 | + |
| 94 | + return $model; |
| 95 | + } |
| 96 | + |
| 97 | + /** @inheritdoc */ |
| 98 | + public function create(array $attributes = [], array $joining = [], $touch = true) |
| 99 | + { |
| 100 | + $instance = $this->related->newInstance($attributes); |
| 101 | + |
| 102 | + // Once we save the related model, we need to attach it to the base model via |
| 103 | + // through intermediate table so we'll use the existing "attach" method to |
| 104 | + // accomplish this which will insert the record and any more attributes. |
| 105 | + $instance->save(['touch' => false]); |
| 106 | + |
| 107 | + $this->attach($instance, $joining, $touch); |
| 108 | + |
| 109 | + return $instance; |
| 110 | + } |
| 111 | + |
| 112 | + /** @inheritdoc */ |
| 113 | + public function sync($ids, $detaching = true) |
| 114 | + { |
| 115 | + $changes = [ |
| 116 | + 'attached' => [], |
| 117 | + 'detached' => [], |
| 118 | + 'updated' => [], |
| 119 | + ]; |
| 120 | + |
| 121 | + if ($ids instanceof Collection) { |
| 122 | + $ids = $this->parseIds($ids); |
| 123 | + } elseif ($ids instanceof Model) { |
| 124 | + $ids = $this->parseIds($ids); |
| 125 | + } |
| 126 | + |
| 127 | + // First we need to attach any of the associated models that are not currently |
| 128 | + // in this joining table. We'll spin through the given IDs, checking to see |
| 129 | + // if they exist in the array of current ones, and if not we will insert. |
| 130 | + if ($this->getInverse()) { |
| 131 | + $current = $this->extractIds($this->parent->{$this->table} ?: []); |
| 132 | + } else { |
| 133 | + $current = $this->parent->{$this->relatedPivotKey} ?: []; |
| 134 | + } |
| 135 | + |
| 136 | + // See issue #256. |
| 137 | + if ($current instanceof Collection) { |
| 138 | + $current = $this->parseIds($current); |
| 139 | + } |
| 140 | + |
| 141 | + $records = $this->formatRecordsList($ids); |
| 142 | + |
| 143 | + $current = Arr::wrap($current); |
| 144 | + |
| 145 | + $detach = array_diff($current, array_keys($records)); |
| 146 | + |
| 147 | + // We need to make sure we pass a clean array, so that it is not interpreted |
| 148 | + // as an associative array. |
| 149 | + $detach = array_values($detach); |
| 150 | + |
| 151 | + // Next, we will take the differences of the currents and given IDs and detach |
| 152 | + // all of the entities that exist in the "current" array but are not in the |
| 153 | + // the array of the IDs given to the method which will complete the sync. |
| 154 | + if ($detaching && count($detach) > 0) { |
| 155 | + $this->detach($detach); |
| 156 | + |
| 157 | + $changes['detached'] = array_map(function ($v) { |
| 158 | + return is_numeric($v) ? (int) $v : (string) $v; |
| 159 | + }, $detach); |
| 160 | + } |
| 161 | + |
| 162 | + // Now we are finally ready to attach the new records. Note that we'll disable |
| 163 | + // touching until after the entire operation is complete so we don't fire a |
| 164 | + // ton of touch operations until we are totally done syncing the records. |
| 165 | + $changes = array_merge( |
| 166 | + $changes, |
| 167 | + $this->attachNew($records, $current, false), |
| 168 | + ); |
| 169 | + |
| 170 | + if (count($changes['attached']) || count($changes['updated'])) { |
| 171 | + $this->touchIfTouching(); |
| 172 | + } |
| 173 | + |
| 174 | + return $changes; |
| 175 | + } |
| 176 | + |
| 177 | + /** @inheritdoc */ |
| 178 | + public function updateExistingPivot($id, array $attributes, $touch = true) |
| 179 | + { |
| 180 | + // Do nothing, we have no pivot table. |
| 181 | + } |
| 182 | + |
| 183 | + /** @inheritdoc */ |
| 184 | + public function attach($id, array $attributes = [], $touch = true) |
| 185 | + { |
| 186 | + if ($id instanceof Model) { |
| 187 | + $model = $id; |
| 188 | + |
| 189 | + $id = $this->parseId($model); |
| 190 | + |
| 191 | + if ($this->getInverse()) { |
| 192 | + // Attach the new ids to the parent model. |
| 193 | + $this->parent->push($this->table, [ |
| 194 | + [ |
| 195 | + $this->relatedPivotKey => $model->{$this->relatedKey}, |
| 196 | + $this->morphType => $model->getMorphClass(), |
| 197 | + ], |
| 198 | + ], true); |
| 199 | + |
| 200 | + // Attach the new parent id to the related model. |
| 201 | + $model->push($this->foreignPivotKey, $this->parseIds($this->parent), true); |
| 202 | + } else { |
| 203 | + // Attach the new parent id to the related model. |
| 204 | + $model->push($this->table, [ |
| 205 | + [ |
| 206 | + $this->foreignPivotKey => $this->parent->{$this->parentKey}, |
| 207 | + $this->morphType => $this->parent instanceof Model ? $this->parent->getMorphClass() : null, |
| 208 | + ], |
| 209 | + ], true); |
| 210 | + |
| 211 | + // Attach the new ids to the parent model. |
| 212 | + $this->parent->push($this->relatedPivotKey, (array) $id, true); |
| 213 | + } |
| 214 | + } else { |
| 215 | + if ($id instanceof Collection) { |
| 216 | + $id = $this->parseIds($id); |
| 217 | + } |
| 218 | + |
| 219 | + $id = (array) $id; |
| 220 | + |
| 221 | + $query = $this->newRelatedQuery(); |
| 222 | + $query->whereIn($this->relatedKey, $id); |
| 223 | + |
| 224 | + if ($this->getInverse()) { |
| 225 | + // Attach the new parent id to the related model. |
| 226 | + $query->push($this->foreignPivotKey, $this->parent->{$this->parentKey}); |
| 227 | + |
| 228 | + // Attach the new ids to the parent model. |
| 229 | + foreach ($id as $item) { |
| 230 | + $this->parent->push($this->table, [ |
| 231 | + [ |
| 232 | + $this->relatedPivotKey => $item, |
| 233 | + $this->morphType => $this->related instanceof Model ? $this->related->getMorphClass() : null, |
| 234 | + ], |
| 235 | + ], true); |
| 236 | + } |
| 237 | + } else { |
| 238 | + // Attach the new parent id to the related model. |
| 239 | + $query->push($this->table, [ |
| 240 | + [ |
| 241 | + $this->foreignPivotKey => $this->parent->{$this->parentKey}, |
| 242 | + $this->morphType => $this->parent instanceof Model ? $this->parent->getMorphClass() : null, |
| 243 | + ], |
| 244 | + ], true); |
| 245 | + |
| 246 | + // Attach the new ids to the parent model. |
| 247 | + $this->parent->push($this->relatedPivotKey, $id, true); |
| 248 | + } |
| 249 | + } |
| 250 | + |
| 251 | + if ($touch) { |
| 252 | + $this->touchIfTouching(); |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + /** @inheritdoc */ |
| 257 | + public function detach($ids = [], $touch = true) |
| 258 | + { |
| 259 | + if ($ids instanceof Model) { |
| 260 | + $ids = $this->parseIds($ids); |
| 261 | + } |
| 262 | + |
| 263 | + $query = $this->newRelatedQuery(); |
| 264 | + |
| 265 | + // If associated IDs were passed to the method we will only delete those |
| 266 | + // associations, otherwise all the association ties will be broken. |
| 267 | + // We'll return the numbers of affected rows when we do the deletes. |
| 268 | + $ids = (array) $ids; |
| 269 | + |
| 270 | + // Detach all ids from the parent model. |
| 271 | + if ($this->getInverse()) { |
| 272 | + // Remove the relation from the parent. |
| 273 | + $data = []; |
| 274 | + foreach ($ids as $item) { |
| 275 | + $data = array_merge($data, [ |
| 276 | + [ |
| 277 | + $this->relatedPivotKey => $item, |
| 278 | + $this->morphType => $this->related->getMorphClass(), |
| 279 | + ], |
| 280 | + ]); |
| 281 | + } |
| 282 | + |
| 283 | + $this->parent->pull($this->table, $data); |
| 284 | + |
| 285 | + // Prepare the query to select all related objects. |
| 286 | + if (count($ids) > 0) { |
| 287 | + $query->whereIn($this->relatedKey, $ids); |
| 288 | + } |
| 289 | + |
| 290 | + // Remove the relation from the related. |
| 291 | + $query->pull($this->foreignPivotKey, $this->parent->{$this->parentKey}); |
| 292 | + } else { |
| 293 | + // Remove the relation from the parent. |
| 294 | + $this->parent->pull($this->relatedPivotKey, $ids); |
| 295 | + |
| 296 | + // Prepare the query to select all related objects. |
| 297 | + if (count($ids) > 0) { |
| 298 | + $query->whereIn($this->relatedKey, $ids); |
| 299 | + } |
| 300 | + |
| 301 | + // Remove the relation to the related. |
| 302 | + $query->pull($this->table, [ |
| 303 | + [ |
| 304 | + $this->foreignPivotKey => $this->parent->{$this->parentKey}, |
| 305 | + $this->morphType => $this->parent->getMorphClass(), |
| 306 | + ], |
| 307 | + ]); |
| 308 | + } |
| 309 | + |
| 310 | + if ($touch) { |
| 311 | + $this->touchIfTouching(); |
| 312 | + } |
| 313 | + |
| 314 | + return count($ids); |
| 315 | + } |
| 316 | + |
| 317 | + /** @inheritdoc */ |
| 318 | + protected function buildDictionary(Collection $results) |
| 319 | + { |
| 320 | + $foreign = $this->foreignPivotKey; |
| 321 | + |
| 322 | + // First we will build a dictionary of child models keyed by the foreign key |
| 323 | + // of the relation so that we will easily and quickly match them to their |
| 324 | + // parents without having a possibly slow inner loops for every models. |
| 325 | + $dictionary = []; |
| 326 | + |
| 327 | + foreach ($results as $result) { |
| 328 | + if ($this->getInverse()) { |
| 329 | + foreach ($result->$foreign as $item) { |
| 330 | + $dictionary[$item][] = $result; |
| 331 | + } |
| 332 | + } else { |
| 333 | + // Collect $foreign value from pivot column of result model |
| 334 | + $items = $this->extractIds($result->{$this->table} ?? [], $foreign); |
| 335 | + foreach ($items as $item) { |
| 336 | + $dictionary[$item][] = $result; |
| 337 | + } |
| 338 | + } |
| 339 | + } |
| 340 | + |
| 341 | + return $dictionary; |
| 342 | + } |
| 343 | + |
| 344 | + /** @inheritdoc */ |
| 345 | + public function newPivotQuery() |
| 346 | + { |
| 347 | + return $this->newRelatedQuery(); |
| 348 | + } |
| 349 | + |
| 350 | + /** |
| 351 | + * Create a new query builder for the related model. |
| 352 | + * |
| 353 | + * @return \Illuminate\Database\Query\Builder |
| 354 | + */ |
| 355 | + public function newRelatedQuery() |
| 356 | + { |
| 357 | + return $this->related->newQuery(); |
| 358 | + } |
| 359 | + |
| 360 | + /** @inheritdoc */ |
| 361 | + public function getQualifiedRelatedPivotKeyName() |
| 362 | + { |
| 363 | + return $this->relatedPivotKey; |
| 364 | + } |
| 365 | + |
| 366 | + /** |
| 367 | + * Get the name of the "where in" method for eager loading. |
| 368 | + * |
| 369 | + * @param string $key |
| 370 | + * |
| 371 | + * @return string |
| 372 | + */ |
| 373 | + protected function whereInMethod(Model $model, $key) |
| 374 | + { |
| 375 | + return 'whereIn'; |
| 376 | + } |
| 377 | + |
| 378 | + /** |
| 379 | + * Extract ids from given pivot table data |
| 380 | + * |
| 381 | + * @param array $data |
| 382 | + * @param string|null $relatedPivotKey |
| 383 | + * |
| 384 | + * @return mixed |
| 385 | + */ |
| 386 | + public function extractIds(array $data, ?string $relatedPivotKey = null) |
| 387 | + { |
| 388 | + $relatedPivotKey = $relatedPivotKey ?: $this->relatedPivotKey; |
| 389 | + return array_reduce($data, function ($carry, $item) use ($relatedPivotKey) { |
| 390 | + if (is_array($item) && array_key_exists($relatedPivotKey, $item)) { |
| 391 | + $carry[] = $item[$relatedPivotKey]; |
| 392 | + } |
| 393 | + |
| 394 | + return $carry; |
| 395 | + }, []); |
| 396 | + } |
| 397 | +} |
0 commit comments