1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SleepingOwl\Admin\Form\Related\Forms; |
4
|
|
|
|
5
|
|
|
use SleepingOwl\Admin\Form\Related\Elements; |
6
|
|
|
|
7
|
|
|
class HasMany extends Elements |
8
|
|
|
{ |
9
|
|
|
public function initialize() |
10
|
|
|
{ |
11
|
|
|
parent::initialize(); |
12
|
|
|
|
13
|
|
|
$this->modifyQuery(function ($query) { |
14
|
|
|
$query->orderBy($this->getEmptyRelation()->getRelated()->getKeyName()); |
15
|
|
|
}); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
protected function proceedSave(\Illuminate\Http\Request $request) |
19
|
|
|
{ |
20
|
|
|
$relation = $this->getRelation(); |
21
|
|
|
|
22
|
|
|
// First we need to remove all entities |
23
|
|
|
if (! $this->toRemove->isEmpty()) { |
24
|
|
|
$class = get_class($relation->getRelated()); |
25
|
|
|
$class::destroy($this->toRemove->all()); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$relation->saveMany($this->relatedValues); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
protected function prepareRelatedValues(array $data) |
32
|
|
|
{ |
33
|
|
|
$elements = $this->flatNamedElements($this->getNewElements()); |
34
|
|
|
foreach ($data as $relatedId => $attributes) { |
35
|
|
|
$related = $this->addOrGetRelated($relatedId); |
36
|
|
|
|
37
|
|
|
foreach ($elements as $element) { |
38
|
|
|
$attribute = $element->getModelAttributeKey(); |
39
|
|
|
$value = $element->prepareValue(array_get($attributes, $attribute)); |
40
|
|
|
$related->setAttribute($attribute, $value); |
41
|
|
|
$element->setModel($related); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
protected function retrieveRelationValuesFromQuery($query) |
47
|
|
|
{ |
48
|
|
|
return $query->get()->keyBy($this->getRelation()->getRelated()->getKeyName()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected function getModelForElements() |
52
|
|
|
{ |
53
|
|
|
return $this->getEmptyRelation()->getRelated(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Returns fresh instance of model for each element in form. |
58
|
|
|
* |
59
|
|
|
* @return \Illuminate\Database\Eloquent\Model |
60
|
|
|
*/ |
61
|
|
|
protected function getFreshModelForElements() |
62
|
|
|
{ |
63
|
|
|
$class = get_class($this->getEmptyRelation()->getRelated()); |
64
|
|
|
|
65
|
|
|
return new $class(); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|