|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vetor\Laravel\Collect\Collectable\Models\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use DB; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
7
|
|
|
use Illuminate\Database\Query\JoinClause; |
|
8
|
|
|
use Vetor\Contracts\Collect\Collection\Models\Collection as CollectionContract; |
|
9
|
|
|
use Vetor\Contracts\Collect\Collectable\Services\CollectableService as CollectableServiceContract; |
|
10
|
|
|
|
|
11
|
|
|
trait Collectable |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @return mixed |
|
15
|
|
|
*/ |
|
16
|
8 |
|
public function collections() |
|
17
|
|
|
{ |
|
18
|
8 |
|
return $this->morphMany(app(CollectionContract::class), 'collectable'); |
|
|
|
|
|
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param null $userId |
|
|
|
|
|
|
23
|
|
|
*/ |
|
24
|
4 |
|
public function collect($userId = null) |
|
25
|
|
|
{ |
|
26
|
4 |
|
return app(CollectableServiceContract::class)->addCollectionTo($this, $userId); |
|
|
|
|
|
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param null $userId |
|
|
|
|
|
|
31
|
|
|
*/ |
|
32
|
|
|
public function isCollection($userId = null) |
|
33
|
|
|
{ |
|
34
|
|
|
return app(CollectableServiceContract::class)->isCollection($this, $userId); |
|
|
|
|
|
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param null $userId |
|
|
|
|
|
|
39
|
|
|
*/ |
|
40
|
1 |
|
public function cancelCollect($userId = null) |
|
41
|
|
|
{ |
|
42
|
1 |
|
return app(CollectableServiceContract::class)->removeCollectionFrom($this, $userId); |
|
|
|
|
|
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @return int |
|
47
|
|
|
*/ |
|
48
|
1 |
|
public function getCollectionsCountAttribute() |
|
49
|
|
|
{ |
|
50
|
1 |
|
return $this->collections ? $this->collections->count() : 0; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $query |
|
55
|
|
|
* @param string $direction |
|
56
|
|
|
* @return mixed |
|
57
|
|
|
*/ |
|
58
|
1 |
|
public function scopeOrderByCollectionsCount(Builder $query, $direction = 'asc') |
|
59
|
|
|
{ |
|
60
|
1 |
|
$collectable = $query->getModel(); |
|
61
|
|
|
|
|
62
|
|
|
return $query |
|
63
|
1 |
|
->select("{$collectable->getTable()}.*") |
|
64
|
1 |
|
->leftJoin('collections', function (JoinClause $join) use ($collectable) { |
|
65
|
|
|
$join |
|
66
|
1 |
|
->on('collections.collectable_id', '=', "{$collectable->getTable()}.{$collectable->getKeyName()}") |
|
67
|
1 |
|
->where('collections.collectable_type', '=', $collectable->getMorphClass()); |
|
68
|
1 |
|
}) |
|
69
|
1 |
|
->groupBy("{$collectable->getTable()}.{$collectable->getKeyName()}") |
|
70
|
1 |
|
->orderBy(DB::raw("count(collections.id)"), $direction) |
|
71
|
1 |
|
->orderBy("{$collectable->getTable()}.{$collectable->getKeyName()}"); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|