|
1
|
|
|
<?php namespace Bedard\Shop\Models; |
|
2
|
|
|
|
|
3
|
|
|
use Model; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Inventory Model. |
|
7
|
|
|
*/ |
|
8
|
|
|
class Inventory extends Model |
|
9
|
|
|
{ |
|
10
|
|
|
use \October\Rain\Database\Traits\Nullable, |
|
11
|
|
|
\October\Rain\Database\Traits\Validation; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @var string The database table used by the model. |
|
15
|
|
|
*/ |
|
16
|
|
|
public $table = 'bedard_shop_inventories'; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var array Attribute casting |
|
20
|
|
|
*/ |
|
21
|
|
|
protected $casts = [ |
|
22
|
|
|
'quantity' => 'integer', |
|
23
|
|
|
]; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var array Guarded fields |
|
27
|
|
|
*/ |
|
28
|
|
|
protected $guarded = ['*']; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var array Fillable fields |
|
32
|
|
|
*/ |
|
33
|
|
|
protected $fillable = [ |
|
34
|
|
|
'id', |
|
35
|
|
|
'product_id', |
|
36
|
|
|
'quantity', |
|
37
|
|
|
'sku', |
|
38
|
|
|
]; |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @var array Nullable fields |
|
42
|
|
|
*/ |
|
43
|
|
|
protected $nullable = ['sku']; |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @var array Validation rules |
|
47
|
|
|
*/ |
|
48
|
|
|
public $rules = [ |
|
49
|
|
|
'sku' => 'unique:bedard_shop_inventories,sku', |
|
50
|
|
|
'quantity' => 'integer|min:0', |
|
51
|
|
|
]; |
|
52
|
|
|
|
|
53
|
|
|
public $customMessages = [ |
|
54
|
|
|
'sku.unique' => 'bedard.shop::lang.inventories.form.sku_unique_error', |
|
55
|
|
|
]; |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @var array Relations |
|
59
|
|
|
*/ |
|
60
|
|
|
public $belongsTo = [ |
|
61
|
|
|
'product' => [ |
|
62
|
|
|
'Bedard\Shop\Models\Product', |
|
63
|
|
|
], |
|
64
|
|
|
]; |
|
65
|
|
|
|
|
66
|
|
|
public $belongsToMany = [ |
|
67
|
|
|
'optionValues' => [ |
|
68
|
|
|
'Bedard\Shop\Models\OptionValue', |
|
69
|
|
|
'table' => 'bedard_shop_inventory_option_values', |
|
70
|
|
|
], |
|
71
|
|
|
]; |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Before validate. |
|
75
|
|
|
* |
|
76
|
|
|
* @return void |
|
77
|
|
|
*/ |
|
78
|
|
|
public function beforeValidate() |
|
79
|
|
|
{ |
|
80
|
|
|
if ($this->id) { |
|
81
|
|
|
$this->rules['sku'] = 'unique:bedard_shop_inventories,sku,'.$this->id; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
/** |
|
86
|
|
|
* Select inventories with one or more optionValue ids. |
|
87
|
|
|
* |
|
88
|
|
|
* @param \October\Rain\Database\Builder $query |
|
89
|
|
|
* @param array $ids |
|
90
|
|
|
* @return \October\Rain\Database\Builder |
|
91
|
|
|
*/ |
|
92
|
|
|
public function scopeHasOptionValueIds($query, $ids) |
|
93
|
|
|
{ |
|
94
|
|
|
if (! is_array($ids)) { |
|
95
|
|
|
$ids = [ $ids ]; |
|
96
|
|
|
} |
|
97
|
|
|
|
|
98
|
|
|
return $query->whereHas('optionValues', function($optionValue) use ($ids){ |
|
99
|
|
|
return $optionValue->whereIn('id', $ids); |
|
100
|
|
|
}); |
|
101
|
|
|
} |
|
102
|
|
|
} |
|
103
|
|
|
|