|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Rinvex\Cacheable; |
|
6
|
|
|
|
|
7
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany as BaseBelongsToMany; |
|
8
|
|
|
|
|
9
|
|
|
class BelongsToMany extends BaseBelongsToMany |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Execute the query as a "select" statement. |
|
13
|
|
|
* |
|
14
|
|
|
* @param array $columns |
|
15
|
|
|
* |
|
16
|
|
|
* @return \Illuminate\Database\Eloquent\Collection |
|
17
|
|
|
*/ |
|
18
|
|
|
public function get($columns = ['*']) |
|
19
|
|
|
{ |
|
20
|
|
|
$builder = $this->query->applyScopes(); |
|
21
|
|
|
|
|
22
|
|
|
$closure = function () use ($builder, $columns) { |
|
23
|
|
|
// First we'll add the proper select columns onto the query so it is run with |
|
24
|
|
|
// the proper columns. Then, we will get the results and hydrate out pivot |
|
25
|
|
|
// models with the result of those columns as a separate model relation. |
|
26
|
|
|
$columns = $this->query->getQuery()->columns ? [] : $columns; |
|
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
$models = $builder->addSelect( |
|
29
|
|
|
$this->shouldSelect($columns) |
|
30
|
|
|
)->getModels(); |
|
31
|
|
|
|
|
32
|
|
|
$this->hydratePivotRelation($models); |
|
33
|
|
|
|
|
34
|
|
|
// If we actually found models we will also eager load any relationships that |
|
35
|
|
|
// have been specified as needing to be eager loaded. This will solve the |
|
36
|
|
|
// n + 1 query problem for the developer and also increase performance. |
|
37
|
|
|
if (count($models) > 0) { |
|
38
|
|
|
$models = $builder->eagerLoadRelations($models); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $this->related->newCollection($models); |
|
42
|
|
|
}; |
|
43
|
|
|
|
|
44
|
|
|
// Check if cache is enabled |
|
45
|
|
|
if ($builder->getModel()->getCacheLifetime()) { |
|
46
|
|
|
return $builder->getModel()->cacheQuery($builder, $columns, $closure); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
// Cache disabled, just execute query & return result |
|
50
|
|
|
$results = call_user_func($closure); |
|
51
|
|
|
|
|
52
|
|
|
// We're done, let's clean up! |
|
53
|
|
|
$builder->getModel()->resetCacheConfig(); |
|
54
|
|
|
|
|
55
|
|
|
return $results; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
It seems like you are assigning to a variable which was imported through a
usestatement which was not imported by reference.For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.
Change not visible in outer-scope
Change visible in outer-scope