Как использовать дополнительный столбец в сводной таблице

Мне нужно сделать настраиваемое поле, как контрольный список, но в виде таблицы и со вторым полем "заказ".
Вот что у меня есть:

  • Модель 1: Условия с отношениями "belongsToMany"
  • Модель 2: Подсервисы

Эти две модели связаны с таблицей products_service, которая имеет два иностранных ключа плюс столбец «заказ».

Чего я не могу понять, так это:
Как можно сохранить лишнюю информацию с помощью рюкзака.

Я знаю, что могу использовать что-то вроде этого:

$user->roles()->updateExistingPivot($roleId, $attributes);

но куда мне его положить?

Вот мой код:

class Condition extends Model
{
  use CrudTrait;
  use Searchable;

  public function relService()
  {
    //dd($this->belongsToMany(SubService::class, 'conditions_service')->withPivot('weight')->withTimestamps());
            return $this->belongsToMany(SubService::class, 'conditions_service')->withPivot('weight')->withTimestamps();
  }
}

class SubService extends Model
{
  use Searchable;
  use CrudTrait;

  public function conditions()
  {
    return $this->belongsToMany(Condition::class, 'conditions_service')->withPivot('weight')->withTimestamps();
  }
}

Вот мой настраиваемый тип поля:

<!-- select2 -->
<div @include('crud::inc.field_wrapper_attributes') >
    <label>{!! $field['label'] !!}</label>
    @include('crud::inc.field_translatable_icon')
    <?php $entity_model = $crud->getModel(); ?>

    <div class="row">
        <div class="col-sm-12">
            <table id="crudTable" class="table table-bordered table-striped display">
                <thead>
                <tr>
                    @if ($crud->details_row)
                        <th></th> <!-- expand/minimize button column -->
                    @endif

                    {{-- Table columns --}}
                    <th>Seleziona</th>
                    <th>Ordine</th>
                    {{--<th>Ordine <i class="fa fa-arrow-up" aria-hidden="true"></i></th>
                    <th>Ordine <i class="fa fa-arrow-down" aria-hidden="true"></i></th>--}}
                    {{--$tst = $connected_entity_entry->relService->whereIn('id', $connected_entity_entry->id)--}}
                </tr>
                </thead>
                <tbody>
                @foreach ($field['model']::all() as $connected_entity_entry) {{--var_dump((empty($connected_entity_entry->conditions->toArray())?"puppa":(empty($connected_entity_entry->conditions->whereIn('id', $connected_entity_entry->id)->toArray())?"puppa uguale":$connected_entity_entry->conditions->whereIn('id', $connected_entity_entry->id)))) --}}
                {{-- dump($connected_entity_entry->getPriority($connected_entity_entry->id)) --}}
                <tr>
                    <th scope="row">
                        <div class="col-sm-4">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox"
                                           name="{{ $field['name'] }}[]"
                                           value="{{ $connected_entity_entry->id }}"

                                           @if( ( old( $field["name"] ) && in_array($connected_entity_entry->id, old( $field["name"])) ) || (isset($field['value']) && in_array($connected_entity_entry->id, $field['value']->pluck('id', 'id')->toArray())))
                                           checked="checked"
                                            @endif > {!! $connected_entity_entry->{$field['attribute']} !!}
                                </label>
                            </div>
                        </div>
                    </th>
                    <td>{{--@include('crud::fields.number')--}}

                    </td>
                </tr>
                @endforeach
                </tbody>
            </table>
        </div>

        {{-- HINT --}}
        @if (isset($field['hint']))
            <p class="help-block">{!! $field['hint'] !!}</p>
        @endif
    </div>
</div>

Спасибо за помощь! Дэйв


person DaveThe    schedule 24.02.2017    source источник
comment
Я улучшил форматирование вашего вопроса и добавил символ } в конце вашего второго класса, чтобы завершить пример кода.   -  person zx485    schedule 24.02.2017


Ответы (1)


Я нашел решение благодаря плотной команде с его запросом на включение (https://github.com/Laravel-Backpack/CRUD/pull/351)

Вот мой обновленный код:

CrudController:

$this->crud->addField([
        'label'     => 'Servizi legati',
        'type'      => 'checklist_ordered',
        'name'      => 'relService',
        'entity'    => 'relService',
        'attribute' => 'title',
        'model'     => "App\Models\SubService",
        'pivot'     => true,
        'pivotFields' => [
            'weight' => 'Ordinamento',
        ],
    ], 'update/create/both');

Вот мой настраиваемый тип поля:

<!-- select2 -->
<div @include('crud::inc.field_wrapper_attributes') >
    <label>{!! $field['label'] !!}</label>
    @include('crud::inc.field_translatable_icon')
    @if (isset($field['model']))
        <?php $entity_model = $crud->getModel();

        $pivot_entries = null;
        if (isset($entry)) {
            $pivot_entries = $entry->{$field['entity']}->keyBy(function ($item) {
                return $item->getKey();
            });
        }
        ?>
        <div class="row">
            <div class="col-sm-12">
                <table id="crudTable" class="table table-bordered table-striped display">
                    <thead>
                    <tr>
                        @if ($crud->details_row)
                            <th></th> <!-- expand/minimize button column -->
                        @endif

                        {{-- Table columns --}}
                        <th>Seleziona</th>
                        @foreach($field['pivotFields'] as $pivot_chunk)
                            <th>{{$pivot_chunk}}</th>
                        @endforeach

                    </tr>
                    </thead>
                    <tbody>
                    @foreach ($field['model']::all() as $connected_entity_entry) 
                    <tr>
                        <th scope="row">
                            <div class="col-sm-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox"
                                               name="{{ $field['name'] }}[]"
                                               value="{{ $connected_entity_entry->id }}"

                                               @if( ( old( $field["name"] ) && in_array($connected_entity_entry->id, old( $field["name"])) ) || (isset($field['value']) && in_array($connected_entity_entry->id, $field['value']->pluck('id', 'id')->toArray())))
                                               checked="checked"
                                                @endif > {!! $connected_entity_entry->{$field['attribute']} !!}
                                    </label>
                                </div>
                            </div>
                        </th>
                        <td>
                            @foreach(array_chunk($field['pivotFields'], 2, true) as $pivot_chunk)
                                @foreach ($pivot_chunk as $pivot_field => $pivot_name)
                                    <?php
                                    $pivot_attr = null;
                                    if ($pivot_entries) {
                                        if ($pivot_entries->has($connected_entity_entry->getKey())) {
                                            $pivot      = $pivot_entries->get($connected_entity_entry->getKey())->pivot;
                                            $pivot_attr = $pivot->getAttribute($pivot_field);
                                        }
                                    }
                                    ?>
                                    <input type="number"
                                           name="{!! $pivot_field !!}[{{ $connected_entity_entry->getKey() }}]"
                                           value="{{ $pivot_attr }}" @include('crud::inc.field_attributes') />
                                @endforeach
                            @endforeach
                        </td>
                    </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
            @endif
            {{-- HINT --}}
            @if (isset($field['hint']))
                <p class="help-block">{!! $field['hint'] !!}</p>
            @endif
        </div>
</div>
person DaveThe    schedule 25.02.2017