1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Blasttech\EloquentRelatedPlus; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOneOrMany; |
9
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Trait RelatedPlusHelpers |
13
|
|
|
* |
14
|
|
|
* Static helper functions |
15
|
|
|
*/ |
16
|
|
|
trait HelpersTrait |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Return the sql for a query with the bindings replaced with the binding values |
20
|
|
|
* |
21
|
|
|
* @param Builder $builder |
22
|
|
|
* @return string |
23
|
|
|
*/ |
24
|
|
|
public function toSqlWithBindings($builder) |
25
|
|
|
{ |
26
|
|
|
$replacements = $builder->getBindings(); |
27
|
|
|
$sql = $builder->toSql(); |
28
|
|
|
|
29
|
|
|
foreach ($replacements as &$replacement) { |
30
|
|
|
$replacement = addslashes($replacement); |
31
|
|
|
if (!is_numeric($replacement)) { |
32
|
|
|
$replacement = '"' . $replacement . '"'; |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return preg_replace_callback( |
37
|
|
|
'/(\?)(?=(?:[^\'"]|["\'][^\'"]*["\'])*$)/', |
38
|
|
|
function () use (&$replacements) { |
39
|
|
|
return array_shift($replacements); |
40
|
|
|
}, |
41
|
|
|
$sql |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Get table name from column name |
47
|
|
|
* |
48
|
|
|
* @param string $column |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
|
|
public function getTableFromColumn($column) |
52
|
|
|
{ |
53
|
|
|
$periodPos = strpos($column, '.'); |
54
|
|
|
|
55
|
|
|
return ($periodPos === false ? $column : substr($column, 0, $periodPos)); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Remove any global scopes which contain $scopeName in their name |
60
|
|
|
* |
61
|
|
|
* @param RelatedPlusTrait|Model $model |
62
|
|
|
* @param Relation|Builder $query |
63
|
|
|
* @param string $scopeName |
64
|
|
|
* @return Relation|BelongsTo|HasOneOrMany|Builder |
65
|
|
|
*/ |
66
|
|
|
public function removeGlobalScopes($model, $query, $scopeName) |
67
|
|
|
{ |
68
|
|
|
$query->withoutGlobalScopes(collect($model->getGlobalScopes())->keys()->filter(function ( |
|
|
|
|
69
|
|
|
$value |
70
|
|
|
) use ($scopeName) { |
71
|
|
|
return stripos($value, $scopeName) !== false; |
72
|
|
|
})->toArray()); |
73
|
|
|
|
74
|
|
|
return $query; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|