/var/www/hkosl.com/b2b2c/webadmin/libraies/illuminate/database/Eloquent/Relations/BelongsToMany.php


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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
<?php

namespace Illuminate\Database\Eloquent\Relations;

use 
Illuminate\Support\Arr;
use 
Illuminate\Support\Str;
use 
Illuminate\Database\Eloquent\Model;
use 
Illuminate\Database\Eloquent\Builder;
use 
Illuminate\Database\Eloquent\Collection;
use 
Illuminate\Database\Eloquent\ModelNotFoundException;

class 
BelongsToMany extends Relation
{
    
/**
     * The intermediate table for the relation.
     *
     * @var string
     */
    
protected $table;

    
/**
     * The foreign key of the parent model.
     *
     * @var string
     */
    
protected $foreignKey;

    
/**
     * The associated key of the relation.
     *
     * @var string
     */
    
protected $otherKey;

    
/**
     * The "name" of the relationship.
     *
     * @var string
     */
    
protected $relationName;

    
/**
     * The pivot table columns to retrieve.
     *
     * @var array
     */
    
protected $pivotColumns = [];

    
/**
     * Any pivot table restrictions for where clauses.
     *
     * @var array
     */
    
protected $pivotWheres = [];

    
/**
     * Any pivot table restrictions for whereIn clauses.
     *
     * @var array
     */
    
protected $pivotWhereIns = [];

    
/**
     * The custom pivot table column for the created_at timestamp.
     *
     * @var string
     */
    
protected $pivotCreatedAt;

    
/**
     * The custom pivot table column for the updated_at timestamp.
     *
     * @var string
     */
    
protected $pivotUpdatedAt;

    
/**
     * The count of self joins.
     *
     * @var int
     */
    
protected static $selfJoinCount 0;

    
/**
     * Create a new belongs to many relationship instance.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  \Illuminate\Database\Eloquent\Model  $parent
     * @param  string  $table
     * @param  string  $foreignKey
     * @param  string  $otherKey
     * @param  string  $relationName
     * @return void
     */
    
public function __construct(Builder $queryModel $parent$table$foreignKey$otherKey$relationName null)
    {
        
$this->table $table;
        
$this->otherKey $otherKey;
        
$this->foreignKey $foreignKey;
        
$this->relationName $relationName;

        
parent::__construct($query$parent);
    }

    
/**
     * Get the results of the relationship.
     *
     * @return mixed
     */
    
public function getResults()
    {
        return 
$this->get();
    }

    
/**
     * Set a where clause for a pivot table column.
     *
     * @param  string  $column
     * @param  string  $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
public function wherePivot($column$operator null$value null$boolean 'and')
    {
        
$this->pivotWheres[] = func_get_args();

        return 
$this->where($this->table.'.'.$column$operator$value$boolean);
    }

    
/**
     * Set a "where in" clause for a pivot table column.
     *
     * @param  string  $column
     * @param  mixed   $values
     * @param  string  $boolean
     * @param  bool    $not
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
public function wherePivotIn($column$values$boolean 'and'$not false)
    {
        
$this->pivotWhereIns[] = func_get_args();

        return 
$this->whereIn($this->table.'.'.$column$values$boolean$not);
    }

    
/**
     * Set an "or where" clause for a pivot table column.
     *
     * @param  string  $column
     * @param  string  $operator
     * @param  mixed   $value
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
public function orWherePivot($column$operator null$value null)
    {
        return 
$this->wherePivot($column$operator$value'or');
    }

    
/**
     * Set an "or where in" clause for a pivot table column.
     *
     * @param  string  $column
     * @param  mixed   $values
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
public function orWherePivotIn($column$values)
    {
        return 
$this->wherePivotIn($column$values'or');
    }

    
/**
     * Execute the query and get the first result.
     *
     * @param  array   $columns
     * @return mixed
     */
    
public function first($columns = ['*'])
    {
        
$results $this->take(1)->get($columns);

        return 
count($results) > $results->first() : null;
    }

    
/**
     * Execute the query and get the first result or throw an exception.
     *
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model|static
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    
public function firstOrFail($columns = ['*'])
    {
        if (! 
is_null($model $this->first($columns))) {
            return 
$model;
        }

        throw (new 
ModelNotFoundException)->setModel(get_class($this->parent));
    }

    
/**
     * Execute the query as a "select" statement.
     *
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Collection
     */
    
public function get($columns = ['*'])
    {
        
// First we'll add the proper select columns onto the query so it is run with
        // the proper columns. Then, we will get the results and hydrate out pivot
        // models with the result of those columns as a separate model relation.
        
$columns $this->query->getQuery()->columns ? [] : $columns;

        
$select $this->getSelectColumns($columns);

        
$builder $this->query->applyScopes();

        
$models $builder->addSelect($select)->getModels();

        
$this->hydratePivotRelation($models);

        
// If we actually found models we will also eager load any relationships that
        // have been specified as needing to be eager loaded. This will solve the
        // n + 1 query problem for the developer and also increase performance.
        
if (count($models) > 0) {
            
$models $builder->eagerLoadRelations($models);
        }

        return 
$this->related->newCollection($models);
    }

    
/**
     * Get a paginator for the "select" statement.
     *
     * @param  int  $perPage
     * @param  array  $columns
     * @param  string  $pageName
     * @param  int|null  $page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    
public function paginate($perPage null$columns = ['*'], $pageName 'page'$page null)
    {
        
$this->query->addSelect($this->getSelectColumns($columns));

        
$paginator $this->query->paginate($perPage$columns$pageName$page);

        
$this->hydratePivotRelation($paginator->items());

        return 
$paginator;
    }

    
/**
     * Paginate the given query into a simple paginator.
     *
     * @param  int  $perPage
     * @param  array  $columns
     * @param  string  $pageName
     * @param  int|null  $page
     * @return \Illuminate\Contracts\Pagination\Paginator
     */
    
public function simplePaginate($perPage null$columns = ['*'], $pageName 'page'$page null)
    {
        
$this->query->addSelect($this->getSelectColumns($columns));

        
$paginator $this->query->simplePaginate($perPage$columns$pageName$page);

        
$this->hydratePivotRelation($paginator->items());

        return 
$paginator;
    }

    
/**
     * Chunk the results of the query.
     *
     * @param  int  $count
     * @param  callable  $callback
     * @return bool
     */
    
public function chunk($countcallable $callback)
    {
        
$this->query->addSelect($this->getSelectColumns());

        return 
$this->query->chunk($count, function ($results) use ($callback) {
            
$this->hydratePivotRelation($results->all());

            return 
$callback($results);
        });
    }

    
/**
     * Hydrate the pivot table relationship on the models.
     *
     * @param  array  $models
     * @return void
     */
    
protected function hydratePivotRelation(array $models)
    {
        
// To hydrate the pivot relationship, we will just gather the pivot attributes
        // and create a new Pivot model, which is basically a dynamic model that we
        // will set the attributes, table, and connections on so it they be used.
        
foreach ($models as $model) {
            
$pivot $this->newExistingPivot($this->cleanPivotAttributes($model));

            
$model->setRelation('pivot'$pivot);
        }
    }

    
/**
     * Get the pivot attributes from a model.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return array
     */
    
protected function cleanPivotAttributes(Model $model)
    {
        
$values = [];

        foreach (
$model->getAttributes() as $key => $value) {
            
// To get the pivots attributes we will just take any of the attributes which
            // begin with "pivot_" and add those to this arrays, as well as unsetting
            // them from the parent's models since they exist in a different table.
            
if (strpos($key'pivot_') === 0) {
                
$values[substr($key6)] = $value;

                unset(
$model->$key);
            }
        }

        return 
$values;
    }

    
/**
     * Set the base constraints on the relation query.
     *
     * @return void
     */
    
public function addConstraints()
    {
        
$this->setJoin();

        if (static::
$constraints) {
            
$this->setWhere();
        }
    }

    
/**
     * Add the constraints for a relationship query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  \Illuminate\Database\Eloquent\Builder  $parent
     * @param  array|mixed  $columns
     * @return \Illuminate\Database\Eloquent\Builder
     */
    
public function getRelationQuery(Builder $queryBuilder $parent$columns = ['*'])
    {
        if (
$parent->getQuery()->from == $query->getQuery()->from) {
            return 
$this->getRelationQueryForSelfJoin($query$parent$columns);
        }

        
$this->setJoin($query);

        return 
parent::getRelationQuery($query$parent$columns);
    }

    
/**
     * Add the constraints for a relationship query on the same table.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  \Illuminate\Database\Eloquent\Builder  $parent
     * @param  array|mixed  $columns
     * @return \Illuminate\Database\Eloquent\Builder
     */
    
public function getRelationQueryForSelfJoin(Builder $queryBuilder $parent$columns = ['*'])
    {
        
$query->select($columns);

        
$query->from($this->related->getTable().' as '.$hash $this->getRelationCountHash());

        
$this->related->setTable($hash);

        
$this->setJoin($query);

        return 
parent::getRelationQuery($query$parent$columns);
    }

    
/**
     * Get a relationship join table hash.
     *
     * @return string
     */
    
public function getRelationCountHash()
    {
        return 
'laravel_reserved_'.static::$selfJoinCount++;
    }

    
/**
     * Set the select clause for the relation query.
     *
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
protected function getSelectColumns(array $columns = ['*'])
    {
        if (
$columns == ['*']) {
            
$columns = [$this->related->getTable().'.*'];
        }

        return 
array_merge($columns$this->getAliasedPivotColumns());
    }

    
/**
     * Get the pivot columns for the relation.
     *
     * @return array
     */
    
protected function getAliasedPivotColumns()
    {
        
$defaults = [$this->foreignKey$this->otherKey];

        
// We need to alias all of the pivot columns with the "pivot_" prefix so we
        // can easily extract them out of the models and put them into the pivot
        // relationships when they are retrieved and hydrated into the models.
        
$columns = [];

        foreach (
array_merge($defaults$this->pivotColumns) as $column) {
            
$columns[] = $this->table.'.'.$column.' as pivot_'.$column;
        }

        return 
array_unique($columns);
    }

    
/**
     * Determine whether the given column is defined as a pivot column.
     *
     * @param  string  $column
     * @return bool
     */
    
protected function hasPivotColumn($column)
    {
        return 
in_array($column$this->pivotColumns);
    }

    
/**
     * Set the join clause for the relation query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder|null  $query
     * @return $this
     */
    
protected function setJoin($query null)
    {
        
$query $query ?: $this->query;

        
// We need to join to the intermediate table on the related model's primary
        // key column with the intermediate table's foreign key for the related
        // model instance. Then we can set the "where" for the parent models.
        
$baseTable $this->related->getTable();

        
$key $baseTable.'.'.$this->related->getKeyName();

        
$query->join($this->table$key'='$this->getOtherKey());

        return 
$this;
    }

    
/**
     * Set the where clause for the relation query.
     *
     * @return $this
     */
    
protected function setWhere()
    {
        
$foreign $this->getForeignKey();

        
$this->query->where($foreign'='$this->parent->getKey());

        return 
$this;
    }

    
/**
     * Set the constraints for an eager load of the relation.
     *
     * @param  array  $models
     * @return void
     */
    
public function addEagerConstraints(array $models)
    {
        
$this->query->whereIn($this->getForeignKey(), $this->getKeys($models));
    }

    
/**
     * Initialize the relation on a set of models.
     *
     * @param  array   $models
     * @param  string  $relation
     * @return array
     */
    
public function initRelation(array $models$relation)
    {
        foreach (
$models as $model) {
            
$model->setRelation($relation$this->related->newCollection());
        }

        return 
$models;
    }

    
/**
     * Match the eagerly loaded results to their parents.
     *
     * @param  array   $models
     * @param  \Illuminate\Database\Eloquent\Collection  $results
     * @param  string  $relation
     * @return array
     */
    
public function match(array $modelsCollection $results$relation)
    {
        
$dictionary $this->buildDictionary($results);

        
// Once we have an array dictionary of child objects we can easily match the
        // children back to their parent using the dictionary and the keys on the
        // the parent models. Then we will return the hydrated models back out.
        
foreach ($models as $model) {
            if (isset(
$dictionary[$key $model->getKey()])) {
                
$collection $this->related->newCollection($dictionary[$key]);

                
$model->setRelation($relation$collection);
            }
        }

        return 
$models;
    }

    
/**
     * Build model dictionary keyed by the relation's foreign key.
     *
     * @param  \Illuminate\Database\Eloquent\Collection  $results
     * @return array
     */
    
protected function buildDictionary(Collection $results)
    {
        
$foreign $this->foreignKey;

        
// First we will build a dictionary of child models keyed by the foreign key
        // of the relation so that we will easily and quickly match them to their
        // parents without having a possibly slow inner loops for every models.
        
$dictionary = [];

        foreach (
$results as $result) {
            
$dictionary[$result->pivot->$foreign][] = $result;
        }

        return 
$dictionary;
    }

    
/**
     * Touch all of the related models for the relationship.
     *
     * E.g.: Touch all roles associated with this user.
     *
     * @return void
     */
    
public function touch()
    {
        
$key $this->getRelated()->getKeyName();

        
$columns $this->getRelatedFreshUpdate();

        
// If we actually have IDs for the relation, we will run the query to update all
        // the related model's timestamps, to make sure these all reflect the changes
        // to the parent models. This will help us keep any caching synced up here.
        
$ids $this->getRelatedIds();

        if (
count($ids) > 0) {
            
$this->getRelated()->newQuery()->whereIn($key$ids)->update($columns);
        }
    }

    
/**
     * Get all of the IDs for the related models.
     *
     * @return \Illuminate\Support\Collection
     */
    
public function getRelatedIds()
    {
        
$related $this->getRelated();

        
$fullKey $related->getQualifiedKeyName();

        return 
$this->getQuery()->select($fullKey)->pluck($related->getKeyName());
    }

    
/**
     * Save a new model and attach it to the parent model.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  array  $joining
     * @param  bool   $touch
     * @return \Illuminate\Database\Eloquent\Model
     */
    
public function save(Model $model, array $joining = [], $touch true)
    {
        
$model->save(['touch' => false]);

        
$this->attach($model->getKey(), $joining$touch);

        return 
$model;
    }

    
/**
     * Save an array of new models and attach them to the parent model.
     *
     * @param  \Illuminate\Support\Collection|array  $models
     * @param  array  $joinings
     * @return array
     */
    
public function saveMany($models, array $joinings = [])
    {
        foreach (
$models as $key => $model) {
            
$this->save($model, (array) Arr::get($joinings$key), false);
        }

        
$this->touchIfTouching();

        return 
$models;
    }

    
/**
     * Find a related model by its primary key.
     *
     * @param  mixed  $id
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null
     */
    
public function find($id$columns = ['*'])
    {
        if (
is_array($id)) {
            return 
$this->findMany($id$columns);
        }

        
$this->where($this->getRelated()->getQualifiedKeyName(), '='$id);

        return 
$this->first($columns);
    }

    
/**
     * Find multiple related models by their primary keys.
     *
     * @param  mixed  $ids
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Collection
     */
    
public function findMany($ids$columns = ['*'])
    {
        if (empty(
$ids)) {
            return 
$this->getRelated()->newCollection();
        }

        
$this->whereIn($this->getRelated()->getQualifiedKeyName(), $ids);

        return 
$this->get($columns);
    }

    
/**
     * Find a related model by its primary key or throw an exception.
     *
     * @param  mixed  $id
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    
public function findOrFail($id$columns = ['*'])
    {
        
$result $this->find($id$columns);

        if (
is_array($id)) {
            if (
count($result) == count(array_unique($id))) {
                return 
$result;
            }
        } elseif (! 
is_null($result)) {
            return 
$result;
        }

        throw (new 
ModelNotFoundException)->setModel(get_class($this->parent));
    }

    
/**
     * Find a related model by its primary key or return new instance of the related model.
     *
     * @param  mixed  $id
     * @param  array  $columns
     * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model
     */
    
public function findOrNew($id$columns = ['*'])
    {
        if (
is_null($instance $this->find($id$columns))) {
            
$instance $this->getRelated()->newInstance();
        }

        return 
$instance;
    }

    
/**
     * Get the first related model record matching the attributes or instantiate it.
     *
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Model
     */
    
public function firstOrNew(array $attributes)
    {
        if (
is_null($instance $this->where($attributes)->first())) {
            
$instance $this->related->newInstance($attributes);
        }

        return 
$instance;
    }

    
/**
     * Get the first related record matching the attributes or create it.
     *
     * @param  array  $attributes
     * @param  array  $joining
     * @param  bool   $touch
     * @return \Illuminate\Database\Eloquent\Model
     */
    
public function firstOrCreate(array $attributes, array $joining = [], $touch true)
    {
        if (
is_null($instance $this->where($attributes)->first())) {
            
$instance $this->create($attributes$joining$touch);
        }

        return 
$instance;
    }

    
/**
     * Create or update a related record matching the attributes, and fill it with values.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @param  array  $joining
     * @param  bool   $touch
     * @return \Illuminate\Database\Eloquent\Model
     */
    
public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch true)
    {
        if (
is_null($instance $this->where($attributes)->first())) {
            return 
$this->create($values$joining$touch);
        }

        
$instance->fill($values);

        
$instance->save(['touch' => false]);

        return 
$instance;
    }

    
/**
     * Create a new instance of the related model.
     *
     * @param  array  $attributes
     * @param  array  $joining
     * @param  bool   $touch
     * @return \Illuminate\Database\Eloquent\Model
     */
    
public function create(array $attributes, array $joining = [], $touch true)
    {
        
$instance $this->related->newInstance($attributes);

        
// Once we save the related model, we need to attach it to the base model via
        // through intermediate table so we'll use the existing "attach" method to
        // accomplish this which will insert the record and any more attributes.
        
$instance->save(['touch' => false]);

        
$this->attach($instance->getKey(), $joining$touch);

        return 
$instance;
    }

    
/**
     * Create an array of new instances of the related models.
     *
     * @param  array  $records
     * @param  array  $joinings
     * @return array
     */
    
public function createMany(array $records, array $joinings = [])
    {
        
$instances = [];

        foreach (
$records as $key => $record) {
            
$instances[] = $this->create($record, (array) Arr::get($joinings$key), false);
        }

        
$this->touchIfTouching();

        return 
$instances;
    }

    
/**
     * Toggles a model (or models) from the parent.
     *
     * Each existing model is detached, and non existing ones are attached.
     *
     * @param  mixed  $ids
     * @param  bool   $touch
     * @return array
     */
    
public function toggle($ids$touch true)
    {
        
$changes = [
            
'attached' => [], 'detached' => [],
        ];

        if (
$ids instanceof Model) {
            
$ids $ids->getKey();
        }

        if (
$ids instanceof Collection) {
            
$ids $ids->modelKeys();
        }

        
// First we will execute a query to get all of the current attached IDs for
        // the relationship, which will allow us to determine which of them will
        // be attached and which of them will be detached from the join table.
        
$current $this->newPivotQuery()
                    ->
pluck($this->otherKey)->all();

        
$records $this->formatRecordsList((array) $ids);

        
// Next, we will determine which IDs should get removed from the join table
        // by checking which of the given ID / records is in the list of current
        // records. We will then remove all those rows from the joining table.
        
$detach array_values(array_intersect(
            
$currentarray_keys($records)
        ));

        if (
count($detach) > 0) {
            
$this->detach($detachfalse);

            
$changes['detached'] = $this->castKeys($detach);
        }

        
// Finally, for all of the records that were not detached, we'll attach the
        // records into the intermediate table. Then we'll add those attaches to
        // the change list and be ready to return these results to the caller.
        
$attach array_diff_key($recordsarray_flip($detach));

        if (
count($attach) > 0) {
            
$this->attach($attach, [], false);

            
$changes['attached'] = array_keys($attach);
        }

        if (
$touch && (count($changes['attached']) || count($changes['detached']))) {
            
$this->touchIfTouching();
        }

        return 
$changes;
    }

    
/**
     * Sync the intermediate tables with a list of IDs without detaching.
     *
     * @param  \Illuminate\Database\Eloquent\Collection|array  $ids
     * @return array
     */
    
public function syncWithoutDetaching($ids)
    {
        return 
$this->sync($idsfalse);
    }

    
/**
     * Sync the intermediate tables with a list of IDs or collection of models.
     *
     * @param  \Illuminate\Database\Eloquent\Collection|array  $ids
     * @param  bool   $detaching
     * @return array
     */
    
public function sync($ids$detaching true)
    {
        
$changes = [
            
'attached' => [], 'detached' => [], 'updated' => [],
        ];

        if (
$ids instanceof Collection) {
            
$ids $ids->modelKeys();
        }

        
// First we need to attach any of the associated models that are not currently
        // in this joining table. We'll spin through the given IDs, checking to see
        // if they exist in the array of current ones, and if not we will insert.
        
$current $this->newPivotQuery()->pluck($this->otherKey)->all();

        
$records $this->formatRecordsList($ids);

        
$detach array_diff($currentarray_keys($records));

        
// Next, we will take the differences of the currents and given IDs and detach
        // all of the entities that exist in the "current" array but are not in the
        // array of the new IDs given to the method which will complete the sync.
        
if ($detaching && count($detach) > 0) {
            
$this->detach($detach);

            
$changes['detached'] = $this->castKeys($detach);
        }

        
// Now we are finally ready to attach the new records. Note that we'll disable
        // touching until after the entire operation is complete so we don't fire a
        // ton of touch operations until we are totally done syncing the records.
        
$changes array_merge(
            
$changes$this->attachNew($records$currentfalse)
        );

        if (
count($changes['attached']) || count($changes['updated'])) {
            
$this->touchIfTouching();
        }

        return 
$changes;
    }

    
/**
     * Format the sync/toggle list so that it is keyed by ID.
     *
     * @param  array  $records
     * @return array
     */
    
protected function formatRecordsList(array $records)
    {
        
$results = [];

        foreach (
$records as $id => $attributes) {
            if (! 
is_array($attributes)) {
                list(
$id$attributes) = [$attributes, []];
            }

            
$results[$id] = $attributes;
        }

        return 
$results;
    }

    
/**
     * Attach all of the IDs that aren't in the current array.
     *
     * @param  array  $records
     * @param  array  $current
     * @param  bool   $touch
     * @return array
     */
    
protected function attachNew(array $records, array $current$touch true)
    {
        
$changes = ['attached' => [], 'updated' => []];

        foreach (
$records as $id => $attributes) {
            
// If the ID is not in the list of existing pivot IDs, we will insert a new pivot
            // record, otherwise, we will just update this existing record on this joining
            // table, so that the developers will easily update these records pain free.
            
if (! in_array($id$current)) {
                
$this->attach($id$attributes$touch);

                
$changes['attached'][] = is_numeric($id) ? (int) $id : (string) $id;
            }

            
// Now we'll try to update an existing pivot record with the attributes that were
            // given to the method. If the model is actually updated we will add it to the
            // list of updated pivot records so we return them back out to the consumer.
            
elseif (count($attributes) > &&
                
$this->updateExistingPivot($id$attributes$touch)) {
                
$changes['updated'][] = is_numeric($id) ? (int) $id : (string) $id;
            }
        }

        return 
$changes;
    }

    
/**
     * Cast the given keys to integers if they are numeric and string otherwise.
     *
     * @param  array  $keys
     * @return array
     */
    
protected function castKeys(array $keys)
    {
        return (array) 
array_map(function ($v) {
            return 
is_numeric($v) ? (int) $v : (string) $v;
        }, 
$keys);
    }

    
/**
     * Update an existing pivot record on the table.
     *
     * @param  mixed  $id
     * @param  array  $attributes
     * @param  bool   $touch
     * @return int
     */
    
public function updateExistingPivot($id, array $attributes$touch true)
    {
        if (
in_array($this->updatedAt(), $this->pivotColumns)) {
            
$attributes $this->setTimestampsOnAttach($attributestrue);
        }

        
$updated $this->newPivotStatementForId($id)->update($attributes);

        if (
$touch) {
            
$this->touchIfTouching();
        }

        return 
$updated;
    }

    
/**
     * Attach a model to the parent.
     *
     * @param  mixed  $id
     * @param  array  $attributes
     * @param  bool   $touch
     * @return void
     */
    
public function attach($id, array $attributes = [], $touch true)
    {
        if (
$id instanceof Model) {
            
$id $id->getKey();
        }

        if (
$id instanceof Collection) {
            
$id $id->modelKeys();
        }

        
$query $this->newPivotStatement();

        
$query->insert($this->createAttachRecords((array) $id$attributes));

        if (
$touch) {
            
$this->touchIfTouching();
        }
    }

    
/**
     * Create an array of records to insert into the pivot table.
     *
     * @param  array  $ids
     * @param  array  $attributes
     * @return array
     */
    
protected function createAttachRecords($ids, array $attributes)
    {
        
$records = [];

        
$timed = ($this->hasPivotColumn($this->createdAt()) ||
                  
$this->hasPivotColumn($this->updatedAt()));

        
// To create the attachment records, we will simply spin through the IDs given
        // and create a new record to insert for each ID. Each ID may actually be a
        // key in the array, with extra attributes to be placed in other columns.
        
foreach ($ids as $key => $value) {
            
$records[] = $this->attacher($key$value$attributes$timed);
        }

        return 
$records;
    }

    
/**
     * Create a full attachment record payload.
     *
     * @param  int    $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @param  bool   $timed
     * @return array
     */
    
protected function attacher($key$value$attributes$timed)
    {
        list(
$id$extra) = $this->getAttachId($key$value$attributes);

        
// To create the attachment records, we will simply spin through the IDs given
        // and create a new record to insert for each ID. Each ID may actually be a
        // key in the array, with extra attributes to be placed in other columns.
        
$record $this->createAttachRecord($id$timed);

        return 
array_merge($record$extra);
    }

    
/**
     * Get the attach record ID and extra attributes.
     *
     * @param  mixed  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return array
     */
    
protected function getAttachId($key$value, array $attributes)
    {
        if (
is_array($value)) {
            return [
$keyarray_merge($value$attributes)];
        }

        return [
$value$attributes];
    }

    
/**
     * Create a new pivot attachment record.
     *
     * @param  int   $id
     * @param  bool  $timed
     * @return array
     */
    
protected function createAttachRecord($id$timed)
    {
        
$record[$this->foreignKey] = $this->parent->getKey();

        
$record[$this->otherKey] = $id;

        
// If the record needs to have creation and update timestamps, we will make
        // them by calling the parent model's "freshTimestamp" method which will
        // provide us with a fresh timestamp in this model's preferred format.
        
if ($timed) {
            
$record $this->setTimestampsOnAttach($record);
        }

        return 
$record;
    }

    
/**
     * Set the creation and update timestamps on an attach record.
     *
     * @param  array  $record
     * @param  bool   $exists
     * @return array
     */
    
protected function setTimestampsOnAttach(array $record$exists false)
    {
        
$fresh $this->parent->freshTimestamp();

        if (! 
$exists && $this->hasPivotColumn($this->createdAt())) {
            
$record[$this->createdAt()] = $fresh;
        }

        if (
$this->hasPivotColumn($this->updatedAt())) {
            
$record[$this->updatedAt()] = $fresh;
        }

        return 
$record;
    }

    
/**
     * Detach models from the relationship.
     *
     * @param  mixed  $ids
     * @param  bool  $touch
     * @return int
     */
    
public function detach($ids = [], $touch true)
    {
        if (
$ids instanceof Model) {
            
$ids $ids->getKey();
        }

        if (
$ids instanceof Collection) {
            
$ids $ids->modelKeys();
        }

        
$query $this->newPivotQuery();

        
// If associated IDs were passed to the method we will only delete those
        // associations, otherwise all of the association ties will be broken.
        // We'll return the numbers of affected rows when we do the deletes.
        
$ids = (array) $ids;

        if (
count($ids) > 0) {
            
$query->whereIn($this->otherKey$ids);
        }

        
// Once we have all of the conditions set on the statement, we are ready
        // to run the delete on the pivot table. Then, if the touch parameter
        // is true, we will go ahead and touch all related models to sync.
        
$results $query->delete();

        if (
$touch) {
            
$this->touchIfTouching();
        }

        return 
$results;
    }

    
/**
     * If we're touching the parent model, touch.
     *
     * @return void
     */
    
public function touchIfTouching()
    {
        if (
$this->touchingParent()) {
            
$this->getParent()->touch();
        }

        if (
$this->getParent()->touches($this->relationName)) {
            
$this->touch();
        }
    }

    
/**
     * Determine if we should touch the parent on sync.
     *
     * @return bool
     */
    
protected function touchingParent()
    {
        return 
$this->getRelated()->touches($this->guessInverseRelation());
    }

    
/**
     * Attempt to guess the name of the inverse of the relation.
     *
     * @return string
     */
    
protected function guessInverseRelation()
    {
        return 
Str::camel(Str::plural(class_basename($this->getParent())));
    }

    
/**
     * Create a new query builder for the pivot table.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    
protected function newPivotQuery()
    {
        
$query $this->newPivotStatement();

        foreach (
$this->pivotWheres as $whereArgs) {
            
call_user_func_array([$query'where'], $whereArgs);
        }

        foreach (
$this->pivotWhereIns as $whereArgs) {
            
call_user_func_array([$query'whereIn'], $whereArgs);
        }

        return 
$query->where($this->foreignKey$this->parent->getKey());
    }

    
/**
     * Get a new plain query builder for the pivot table.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    
public function newPivotStatement()
    {
        return 
$this->query->getQuery()->newQuery()->from($this->table);
    }

    
/**
     * Get a new pivot statement for a given "other" ID.
     *
     * @param  mixed  $id
     * @return \Illuminate\Database\Query\Builder
     */
    
public function newPivotStatementForId($id)
    {
        return 
$this->newPivotQuery()->where($this->otherKey$id);
    }

    
/**
     * Create a new pivot model instance.
     *
     * @param  array  $attributes
     * @param  bool   $exists
     * @return \Illuminate\Database\Eloquent\Relations\Pivot
     */
    
public function newPivot(array $attributes = [], $exists false)
    {
        
$pivot $this->related->newPivot($this->parent$attributes$this->table$exists);

        return 
$pivot->setPivotKeys($this->foreignKey$this->otherKey);
    }

    
/**
     * Create a new existing pivot model instance.
     *
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Relations\Pivot
     */
    
public function newExistingPivot(array $attributes = [])
    {
        return 
$this->newPivot($attributestrue);
    }

    
/**
     * Set the columns on the pivot table to retrieve.
     *
     * @param  array|mixed  $columns
     * @return $this
     */
    
public function withPivot($columns)
    {
        
$columns is_array($columns) ? $columns func_get_args();

        
$this->pivotColumns array_merge($this->pivotColumns$columns);

        return 
$this;
    }

    
/**
     * Specify that the pivot table has creation and update timestamps.
     *
     * @param  mixed  $createdAt
     * @param  mixed  $updatedAt
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    
public function withTimestamps($createdAt null$updatedAt null)
    {
        
$this->pivotCreatedAt $createdAt;
        
$this->pivotUpdatedAt $updatedAt;

        return 
$this->withPivot($this->createdAt(), $this->updatedAt());
    }

    
/**
     * Get the name of the "created at" column.
     *
     * @return string
     */
    
public function createdAt()
    {
        return 
$this->pivotCreatedAt ?: $this->parent->getCreatedAtColumn();
    }

    
/**
     * Get the name of the "updated at" column.
     *
     * @return string
     */
    
public function updatedAt()
    {
        return 
$this->pivotUpdatedAt ?: $this->parent->getUpdatedAtColumn();
    }

    
/**
     * Get the related model's updated at column name.
     *
     * @return string
     */
    
public function getRelatedFreshUpdate()
    {
        return [
$this->related->getUpdatedAtColumn() => $this->related->freshTimestampString()];
    }

    
/**
     * Get the key for comparing against the parent key in "has" query.
     *
     * @return string
     */
    
public function getHasCompareKey()
    {
        return 
$this->getForeignKey();
    }

    
/**
     * Get the fully qualified foreign key for the relation.
     *
     * @return string
     */
    
public function getForeignKey()
    {
        return 
$this->table.'.'.$this->foreignKey;
    }

    
/**
     * Get the fully qualified "other key" for the relation.
     *
     * @return string
     */
    
public function getOtherKey()
    {
        return 
$this->table.'.'.$this->otherKey;
    }

    
/**
     * Get the intermediate table for the relationship.
     *
     * @return string
     */
    
public function getTable()
    {
        return 
$this->table;
    }

    
/**
     * Get the relationship name for the relationship.
     *
     * @return string
     */
    
public function getRelationName()
    {
        return 
$this->relationName;
    }
}