BelongsToManyThrough::addConstraints()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 12
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 20
rs 9.8666
1
<?php
2
3
namespace Shomisha\UnusualRelationships\Relationships;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
9
class BelongsToManyThrough extends HasMany
10
{
11
    /** @var Model */
12
    protected $through;
13
14
    /** @var string */
15
    protected $foreignOnThrough;
16
17
    /** @var string */
18
    protected $pivotTable;
19
20
    /** @var string */
21
    protected $relatedForeign;
22
23
    /** @var string */
24
    protected $throughForeign;
25
26
    public function __construct(
27
        Builder $query,
28
        Model $parent,
29
        Model $related,
30
        Model $through,
31
        string $foreignOnThrough,
32
        string $pivotTable,
33
        string $relatedForeign,
34
        string $throughForeign
35
    ) {
36
        $this->through = $through;
37
        $this->related = $related;
38
        $this->foreignOnThrough = $foreignOnThrough;
39
        $this->pivotTable = $pivotTable;
40
        $this->relatedForeign = $relatedForeign;
41
        $this->throughForeign = $throughForeign;
42
43
        parent::__construct($query, $parent, $foreignOnThrough, $parent->getKeyName());
44
    }
45
46
    /**
47
     * Constrain the query.
48
     */
49
    public function addConstraints()
50
    {
51
        $relatedTable = $this->related->getTable();
52
        $relatedKey = $this->related->getKeyName();
53
54
        $throughTable = $this->through->getTable();
55
        $throughKey = $this->through->getKeyName();
56
57
        $this->query->select([
58
            "{$relatedTable}.*",
59
            "{$throughTable}.{$this->foreignOnThrough}",
60
        ]);
61
62
        $this->query->join("{$this->pivotTable} as pivot_table", "pivot_table.{$this->relatedForeign}", '=', "{$relatedTable}.{$relatedKey}");
63
        $this->query->join("{$throughTable}", "{$throughTable}.{$throughKey}", '=', "pivot_table.{$this->throughForeign}");
64
65
        $this->query->distinct();
66
67
        if (static::$constraints) {
68
            $this->query->where("{$throughTable}.{$this->foreignOnThrough}", $this->getParentKey());
69
        }
70
    }
71
72
    /**
73
     * Constrain the query for multiple models.
74
     *
75
     * @param array $models
76
     */
77
    public function addEagerConstraints(array $models)
78
    {
79
        $keys = collect($models)->map(function (Model $model) {
80
            return $model->getKey();
81
        });
82
83
        $throughTable = $this->through->getTable();
84
85
        $this->query->whereIn("{$throughTable}.{$this->foreignOnThrough}", $keys);
86
    }
87
}
88