BACKPACK Laravel 使用 Backpack CRUD 在多对多关系中管理 pivot table 中的额外列
BACKPACK Laravel manage extra columns in pivot table in a many-to-many relationship using Backpack CRUD
我正在为 laravel 使用背包,我正在尝试 add/update 在多对多关系中使用的枢轴 table 中的一些额外列。
总结上下文:我有一个模型 Task,另一个模型 Machine 和这个中间枢轴 table machine_task 包含 Task 和 Machine 之间的多对多关系
在这个machine_task中有machine_id,task_id然后是布尔列m(对于'monthly'),q(对于'quarterly'),b (对于 'biannual')和 y(对于 'yearly')。
这就是我的
在我的 Models/Task.php 中,我定义了 m-2-m 关系
public function machines()
{
return $this->belongsToMany('App\Machine')->withPivot('m','q','b','y');
}
在 /app/Http/Controllers/Admin/TaskCrudController.php 我有字段,最相关的是这个
$this->crud->addField([ // n-n relationship
'label' => "Machines", // Table column heading
'type' => "select2_from_ajax_multiple_custom", // a customized field type modifying the standard select2_from_ajax_multiple type
'name' => 'machines', // the column that contains the ID of that connected entity
'entity' => 'machines', // the method that defines the relationship in your Model
'attribute' => "name", // foreign key attribute that is shown to user
'model' => "App\Models\Machine", // foreign key model
'data_source' => url("api/machines"), // url to controller search function (with /{id} should return model)
'placeholder' => "Select machine(s)",
'minimum_input_length' => 0,
'pivot' => true,
'dependencies' => ['building_id'], // this "Machines" field depends on another previous field value
]);
这非常有效:当我创建或更新任务时,AJAX 调用返回正确的结果,值被正确地添加到 select2 输入中,并且 pivot table machine_task 已正确填充并更新为 task_id 和 machine_id当我单击“保存并返回”按钮时。
但是如何将额外的值 m,q,b 插入主元 table 、y 与 task_id 和 machine_id 一起?
在TaskCrudController.php的最后我有
public function store(StoreRequest $request)
{
// your additional operations before save here
// What I should do here to get the pivot values into the request??????????????
$redirect_location = parent::storeCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
public function update(UpdateRequest $request)
{
// your additional operations before save here
// What I should do here to get the pivot values into the request??????????????
$redirect_location = parent::updateCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
在我修改后的 select2_from_ajax_multiple 版本中,我为每个选定的选项添加了一些带有复选框的行。让我们在屏幕截图中看到更好的理解
select2_from_ajax_multiple_custom
在 /vendor/backpack/crud/src/resources/views/fields/select2_from_ajax_multiple_custom.blade.php 中,我像这样初始化值,然后使用 jquery 更新与select2 控件,但我不知道如何将 m、q、b、y 复选框与每个 select2 选定选项相关联并将它们传递给请求。
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<div id="div{{ $item->getKey() }}">
<span> {{ $item->getKey() }} {{ $item->{$field['attribute']} }} -- </span>
Monthly <input type="checkbox" id="m{{ $item->getKey() }}" name="m{{ $item->getKey() }}" value="1" @php if ($item->pivot['m'] == "1") echo "checked"; @endphp >
Quarterly <input type="checkbox" id="q{{ $item->getKey() }}" name="q{{ $item->getKey() }}" value="1" @php if ($item->pivot['q'] == "1") echo "checked"; @endphp>
Biannual <input type="checkbox" id="b{{ $item->getKey() }}" name="b{{ $item->getKey() }}" value="1" @php if ($item->pivot['b'] == "1") echo "checked"; @endphp>
Yearly <input type="checkbox" id="y{{ $item->getKey() }}" name="y{{ $item->getKey() }}"value="1" @php if ($item->pivot['y'] == "1") echo "checked"; @endphp> <br/>
@php
@endphp
</div>
@endforeach
@endif
非常感谢您抽出宝贵时间,希望您能帮助我!有点坚持这个!
我已经能够解决它,所以我会 post 解决方案,因为它可能对其他人有用。
我做了什么,
在我的TaskCrudController.php中,我添加了底层任务模型
// add this to the use statements
use App\Models\Task;
然后,也是在TaskCrudController.php我做了这个
// Notice: You need to add this to "create" function as well, I'm just writing here the update function to keep it short.
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
foreach ($request->machines as $machine) {
$set= array('m'=>'0','t'=> '0', 's' => '0', 'a' => '0');
if (isset($request['m'])) in_array ($machine, $request['m']) ? $set['m'] = '1' : $set['m'] = '0';
if (isset($request['t'])) in_array ($machine, $request['t']) ? $set['q'] = '1' : $set['q'] = '0';
if (isset($request['s'])) in_array ($machine, $request['s']) ? $set['b'] = '1' : $set['b'] = '0';
if (isset($request['a'])) in_array ($machine, $request['a']) ? $set['y'] = '1' : $set['y'] = '0';
Task::find($request->id)->machines()->syncWithoutDetaching([$machine => $set]);
return $redirect_location;
}
// Code explanation:
// what we are doing basically here is to grab the $request data
// For example: In the $request we receive m[3] b[1,3] y[1] arrays
// meaning that for our task:
// Machine 1 has no monthly, no quarterly but biannual and yearly checkboxes checked
// Machine 3 has monthly, no quarterly, biannual and no yearly checkboxes checked
// with the loop above, we cast that incoming data into this structure
// $set would contain after the loop:
// '1' => ['m' => '0', 'q'=> '0', 'b' => '1', 'y' => '1']
// '3' => ['m' => '1', 'q'=> '0', 'b' => '1', 'y' => '0']
// with that, we updated the intermediate table using syncWithoutDetaching
现在让我们看看 select2_from_ajax_multiple_custom.blade.php 虽然我没有 posting 所有代码(其余与 select2_from_ajax_multiple 标准字段相同)
<div @include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
@include('crud::inc.field_translatable_icon')
<select
name="{{ $field['name'] }}[]"
style="width: 100%"
id="select2_ajax_multiple_custom_{{ $field['name'] }}"
@include('crud::inc.field_attributes', ['default_class' => 'form-control'])
multiple>
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<option value="{{ $item->getKey() }}" selected>
{{ $item->{$field['attribute']} }}
</option>
@endforeach
@endif
</select>
// What I added is:
<div id="freq">
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<div id="div{{ $item->getKey() }}">
<span>{{ $item->{$field['attribute']} }} -- </span>
Monthly <input type="checkbox" id="m{{ $item->getKey() }}" name="m[]" value="{{ $item->getKey() }}" @php if ($item->pivot['m'] == "1") echo "checked"; @endphp >
Quarterly <input type="checkbox" id="q{{ $item->getKey() }}" name="q[]" value="{{ $item->getKey() }}" @php if ($item->pivot['q'] == "1") echo "checked"; @endphp>
Biannual <input type="checkbox" id="b{{ $item->getKey() }}" name="b[]" value="{{ $item->getKey() }}" @php if ($item->pivot['b'] == "1") echo "checked"; @endphp>
Yearly <input type="checkbox" id="y{{ $item->getKey() }}" name="y[]"value="{{ $item->getKey() }}" @php if ($item->pivot['y'] == "1") echo "checked"; @endphp> <br/>
</div>
@endforeach
@endif
</div>
// js code to add or remove rows containing the checkboxes (This needs to be put inside <script> tags obviously) $("#select2_ajax_multiple_custom_machines").on("select2:select", function(e) {
// add checkbox row
htmlRow = "<div id=\"div"+e.params.data.id+"\">"+"<span> "+e.params.data.text+"-- </span>"+" Monthly <input type=\"checkbox\" id=\"m"+e.params.data.id+"\" name=\"m[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Quarterly <input type=\"checkbox\" id=\"q"+e.params.data.id+"\" name=\"q[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Biannual <input type=\"checkbox\" id=\"b"+e.params.data.id+"\" name=\"b[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Yearly <input type=\"checkbox\" id=\"y"+e.params.data.id+"\" name=\"y[]\" value=\""+e.params.data.id+"\"><br/>";
htmlRow += "</div>";
$("#freq").append(htmlRow);
});
$("#select2_ajax_multiple_custom_machines").on("select2:unselect", function(e) {
// remove checkbox row
$("#div"+e.params.data.id).remove();
});
伙计们,仅此而已。
希望对你有帮助。
我正在为 laravel 使用背包,我正在尝试 add/update 在多对多关系中使用的枢轴 table 中的一些额外列。
总结上下文:我有一个模型 Task,另一个模型 Machine 和这个中间枢轴 table machine_task 包含 Task 和 Machine 之间的多对多关系
在这个machine_task中有machine_id,task_id然后是布尔列m(对于'monthly'),q(对于'quarterly'),b (对于 'biannual')和 y(对于 'yearly')。
这就是我的
在我的 Models/Task.php 中,我定义了 m-2-m 关系
public function machines()
{
return $this->belongsToMany('App\Machine')->withPivot('m','q','b','y');
}
在 /app/Http/Controllers/Admin/TaskCrudController.php 我有字段,最相关的是这个
$this->crud->addField([ // n-n relationship
'label' => "Machines", // Table column heading
'type' => "select2_from_ajax_multiple_custom", // a customized field type modifying the standard select2_from_ajax_multiple type
'name' => 'machines', // the column that contains the ID of that connected entity
'entity' => 'machines', // the method that defines the relationship in your Model
'attribute' => "name", // foreign key attribute that is shown to user
'model' => "App\Models\Machine", // foreign key model
'data_source' => url("api/machines"), // url to controller search function (with /{id} should return model)
'placeholder' => "Select machine(s)",
'minimum_input_length' => 0,
'pivot' => true,
'dependencies' => ['building_id'], // this "Machines" field depends on another previous field value
]);
这非常有效:当我创建或更新任务时,AJAX 调用返回正确的结果,值被正确地添加到 select2 输入中,并且 pivot table machine_task 已正确填充并更新为 task_id 和 machine_id当我单击“保存并返回”按钮时。
但是如何将额外的值 m,q,b 插入主元 table 、y 与 task_id 和 machine_id 一起?
在TaskCrudController.php的最后我有
public function store(StoreRequest $request)
{
// your additional operations before save here
// What I should do here to get the pivot values into the request??????????????
$redirect_location = parent::storeCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
public function update(UpdateRequest $request)
{
// your additional operations before save here
// What I should do here to get the pivot values into the request??????????????
$redirect_location = parent::updateCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
在我修改后的 select2_from_ajax_multiple 版本中,我为每个选定的选项添加了一些带有复选框的行。让我们在屏幕截图中看到更好的理解
select2_from_ajax_multiple_custom
在 /vendor/backpack/crud/src/resources/views/fields/select2_from_ajax_multiple_custom.blade.php 中,我像这样初始化值,然后使用 jquery 更新与select2 控件,但我不知道如何将 m、q、b、y 复选框与每个 select2 选定选项相关联并将它们传递给请求。
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<div id="div{{ $item->getKey() }}">
<span> {{ $item->getKey() }} {{ $item->{$field['attribute']} }} -- </span>
Monthly <input type="checkbox" id="m{{ $item->getKey() }}" name="m{{ $item->getKey() }}" value="1" @php if ($item->pivot['m'] == "1") echo "checked"; @endphp >
Quarterly <input type="checkbox" id="q{{ $item->getKey() }}" name="q{{ $item->getKey() }}" value="1" @php if ($item->pivot['q'] == "1") echo "checked"; @endphp>
Biannual <input type="checkbox" id="b{{ $item->getKey() }}" name="b{{ $item->getKey() }}" value="1" @php if ($item->pivot['b'] == "1") echo "checked"; @endphp>
Yearly <input type="checkbox" id="y{{ $item->getKey() }}" name="y{{ $item->getKey() }}"value="1" @php if ($item->pivot['y'] == "1") echo "checked"; @endphp> <br/>
@php
@endphp
</div>
@endforeach
@endif
非常感谢您抽出宝贵时间,希望您能帮助我!有点坚持这个!
我已经能够解决它,所以我会 post 解决方案,因为它可能对其他人有用。
我做了什么,
在我的TaskCrudController.php中,我添加了底层任务模型
// add this to the use statements
use App\Models\Task;
然后,也是在TaskCrudController.php我做了这个
// Notice: You need to add this to "create" function as well, I'm just writing here the update function to keep it short.
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
foreach ($request->machines as $machine) {
$set= array('m'=>'0','t'=> '0', 's' => '0', 'a' => '0');
if (isset($request['m'])) in_array ($machine, $request['m']) ? $set['m'] = '1' : $set['m'] = '0';
if (isset($request['t'])) in_array ($machine, $request['t']) ? $set['q'] = '1' : $set['q'] = '0';
if (isset($request['s'])) in_array ($machine, $request['s']) ? $set['b'] = '1' : $set['b'] = '0';
if (isset($request['a'])) in_array ($machine, $request['a']) ? $set['y'] = '1' : $set['y'] = '0';
Task::find($request->id)->machines()->syncWithoutDetaching([$machine => $set]);
return $redirect_location;
}
// Code explanation:
// what we are doing basically here is to grab the $request data
// For example: In the $request we receive m[3] b[1,3] y[1] arrays
// meaning that for our task:
// Machine 1 has no monthly, no quarterly but biannual and yearly checkboxes checked
// Machine 3 has monthly, no quarterly, biannual and no yearly checkboxes checked
// with the loop above, we cast that incoming data into this structure
// $set would contain after the loop:
// '1' => ['m' => '0', 'q'=> '0', 'b' => '1', 'y' => '1']
// '3' => ['m' => '1', 'q'=> '0', 'b' => '1', 'y' => '0']
// with that, we updated the intermediate table using syncWithoutDetaching
现在让我们看看 select2_from_ajax_multiple_custom.blade.php 虽然我没有 posting 所有代码(其余与 select2_from_ajax_multiple 标准字段相同)
<div @include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
@include('crud::inc.field_translatable_icon')
<select
name="{{ $field['name'] }}[]"
style="width: 100%"
id="select2_ajax_multiple_custom_{{ $field['name'] }}"
@include('crud::inc.field_attributes', ['default_class' => 'form-control'])
multiple>
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<option value="{{ $item->getKey() }}" selected>
{{ $item->{$field['attribute']} }}
</option>
@endforeach
@endif
</select>
// What I added is:
<div id="freq">
@if ($old_value)
@foreach ($old_value as $item)
@if (!is_object($item))
@php
$item = $connected_entity->find($item);
@endphp
@endif
<div id="div{{ $item->getKey() }}">
<span>{{ $item->{$field['attribute']} }} -- </span>
Monthly <input type="checkbox" id="m{{ $item->getKey() }}" name="m[]" value="{{ $item->getKey() }}" @php if ($item->pivot['m'] == "1") echo "checked"; @endphp >
Quarterly <input type="checkbox" id="q{{ $item->getKey() }}" name="q[]" value="{{ $item->getKey() }}" @php if ($item->pivot['q'] == "1") echo "checked"; @endphp>
Biannual <input type="checkbox" id="b{{ $item->getKey() }}" name="b[]" value="{{ $item->getKey() }}" @php if ($item->pivot['b'] == "1") echo "checked"; @endphp>
Yearly <input type="checkbox" id="y{{ $item->getKey() }}" name="y[]"value="{{ $item->getKey() }}" @php if ($item->pivot['y'] == "1") echo "checked"; @endphp> <br/>
</div>
@endforeach
@endif
</div>
// js code to add or remove rows containing the checkboxes (This needs to be put inside <script> tags obviously) $("#select2_ajax_multiple_custom_machines").on("select2:select", function(e) {
// add checkbox row
htmlRow = "<div id=\"div"+e.params.data.id+"\">"+"<span> "+e.params.data.text+"-- </span>"+" Monthly <input type=\"checkbox\" id=\"m"+e.params.data.id+"\" name=\"m[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Quarterly <input type=\"checkbox\" id=\"q"+e.params.data.id+"\" name=\"q[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Biannual <input type=\"checkbox\" id=\"b"+e.params.data.id+"\" name=\"b[]\" value=\""+e.params.data.id+"\">";
htmlRow += " Yearly <input type=\"checkbox\" id=\"y"+e.params.data.id+"\" name=\"y[]\" value=\""+e.params.data.id+"\"><br/>";
htmlRow += "</div>";
$("#freq").append(htmlRow);
});
$("#select2_ajax_multiple_custom_machines").on("select2:unselect", function(e) {
// remove checkbox row
$("#div"+e.params.data.id).remove();
});
伙计们,仅此而已。 希望对你有帮助。