|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Signifly\Addresses\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOne; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
|
8
|
|
|
|
|
9
|
|
|
trait HasAddresses |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Boot the addressable trait for the model. |
|
13
|
|
|
* |
|
14
|
|
|
* @return void |
|
15
|
|
|
*/ |
|
16
|
|
|
public static function bootHasAddresses() |
|
17
|
|
|
{ |
|
18
|
|
|
static::deleting(function ($model) { |
|
19
|
|
|
$model->addresses()->delete(); |
|
20
|
|
|
}); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* The associated addresses relation. |
|
25
|
|
|
* |
|
26
|
|
|
* @return \Illuminate\Database\Eloquent\Relations\MorphMany |
|
27
|
|
|
*/ |
|
28
|
|
|
public function addresses(): MorphMany |
|
29
|
|
|
{ |
|
30
|
|
|
return $this->morphMany($this->getAddressModel(), 'addressable'); |
|
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* The associated primary address relation. |
|
35
|
|
|
* |
|
36
|
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasOne |
|
37
|
|
|
*/ |
|
38
|
|
|
public function primaryAddress(): HasOne |
|
39
|
|
|
{ |
|
40
|
|
|
return $this->hasOne($this->getAddressModel(), 'id', 'primary_address_id'); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Get the address model. |
|
45
|
|
|
* |
|
46
|
|
|
* @return string |
|
47
|
|
|
*/ |
|
48
|
|
|
protected function getAddressModel(): string |
|
49
|
|
|
{ |
|
50
|
|
|
return config('addresses.address_model'); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Scope a query to include the primary address. |
|
55
|
|
|
* |
|
56
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $query |
|
57
|
|
|
* @return \Illuminate\Database\Eloquent\Builder |
|
58
|
|
|
*/ |
|
59
|
|
|
public function scopeWithPrimaryAddress(Builder $query): Builder |
|
60
|
|
|
{ |
|
61
|
|
|
$addressModel = $this->getAddressModel(); |
|
62
|
|
|
$tableName = $this->getTable(); |
|
|
|
|
|
|
63
|
|
|
$primaryKey = $this->getKeyName(); |
|
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
return $query->addSelect(['primary_address_id' => $addressModel::select('id') |
|
66
|
|
|
->whereRaw("addressable_id = {$tableName}.{$primaryKey}") |
|
67
|
|
|
->where('addressable_type', get_class()) |
|
68
|
|
|
->primary() |
|
69
|
|
|
->limit(1), |
|
70
|
|
|
])->with('primaryAddress'); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|