Attribute::removeValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Ronmrcdo\Inventory\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
9
class Attribute extends Model
10
{
11
    /**
12
     * Table name of the model
13
     * 
14
     * @var string
15
     */
16
    protected $table = 'product_attributes';
17
18
    /**
19
     * Disable the timestamp on model creation
20
     * 
21
     * @var bool
22
     */
23
    public $timestamps = false;
24
25
    /**
26
     * Fields that are mass assignable
27
     * 
28
     * @var array
29
     */
30
    protected $fillable = [
31
        'product_id', 'name'
32
    ];
33
34
    /**
35
     * Fields that can't be assign
36
     * 
37
     * @var array
38
     */
39
    protected $guarded = [
40
        'id'
41
    ];
42
43
    /**
44
     * Add Value on the attribute
45
     * 
46
     * @param string|array $value
47
     */
48
    public function addValue($value)
49
    {
50
        if (is_array($value)) {
51
            $terms = collect($value)->map(function ($term) {
52
                return ['value' => $term];
53
            })
54
            ->values()
55
            ->toArray();
56
57
            return $this->values()->createMany($terms);
58
        }
59
        return $this->values()->create(['value' => $value]);
60
    }
61
62
    /**
63
     * Remove a term on an attribute
64
     * 
65
     * @param string $term
66
     */
67
    public function removeValue($term)
68
    {
69
        return $this->values()->where('value', $term)->firstOrFail()->delete();
70
    }
71
72
    /**
73
     * Relation of the attribute to the product
74
     * 
75
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo $this
76
     */
77
    public function product(): BelongsTo
78
    {
79
        return $this->belongsTo(config('laravel-inventory.product'));
80
    }
81
82
    /**
83
     * Relation to the values
84
     * 
85
     * @return \Illuminate\Database\Eloquent\Relations\HasMany $this
86
     */
87
    public function values(): HasMany
88
    {
89
        return $this->hasMany('Ronmrcdo\Inventory\Models\AttributeValue', 'product_attribute_id');
90
    }
91
}
92