Как реализовать много-много новых ресурсов без создания специального инструмента - PullRequest
0 голосов
/ 15 октября 2019

В настоящее время я создаю систему генерации расписания, у меня есть следующие модели: Субъект и Учитель . В качестве двух основных моделей с их новыми ресурсами я создал сводную модель. SubjectAllocation (имеет ресурс nova) с сводной таблицей subject_allocations с полями teacher_id и subject_id . Я хотел бы иметь возможность использовать ресурс SubjectAllocation nova, чтобы выбрать учителя и выделить несколько предметов этому учителю, но в настоящее время у меня нет недостатка в нем. Попытался потянуть в этом пакете dillingham / nova-attach-many , чтобы прикрепить к модели SubjectAllocation и этот пакет для выбора учительских записей sloveniangooner / searchable-select , но этоневозможно сохранить данные в сводной таблице.

Ресурс выделения субъекта

<?php

      namespace App\Nova;

      use Illuminate\Http\Request;
      use Laravel\Nova\Fields\BelongsToMany;
      use Laravel\Nova\Fields\ID;
      use Laravel\Nova\Http\Requests\NovaRequest;
      use NovaAttachMany\AttachMany;
      use Sloveniangooner\SearchableSelect\SearchableSelect;

 class SubjectAllocation extends Resource
 {
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
     public static $model = 'App\SubjectAllocation';

     /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
     public static $title = 'id';

     /**
     * The columns that should be searched.
     *
     * @var array
     */
     public static $search = [
       'id',
     ];

/**
 * Get the fields displayed by the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function fields(Request $request)
{
    return [
        ID::make()->sortable(),

        SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),

        AttachMany::make('Subjects')
            ->showCounts()
            ->help('<b>Tip: </b> Select subjects to be allocated to the teacher'),

    ];
}

/**
 * Get the cards available for the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
 public function cards(Request $request)
 {
    return [];
 }

 /**
 * Get the filters available for the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
 public function filters(Request $request)
 {
    return [];
 }

 /**
 * Get the lenses available for the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
  public function lenses(Request $request)
  {
    return [];
  }

  /**
   * Get the actions available for the resource.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return array
   */
   public function actions(Request $request)
   {
      return [];
   }
}

Методы полей в ресурсе объекта

public function fields(Request $request)
{
    return [
        ID::make()->sortable(),

        Text::make('Subject Name', 'name')
            ->withMeta(['extraAttributes' => ['placeholder' => 'Subject Name']])
            ->sortable()
            ->creationRules('required', 'max:255', 'unique:subjects,name')
            ->updateRules('required', 'max:255'),

        Text::make('Subject Code', 'code')
            ->withMeta(['extraAttributes' => ['placeholder' => 'Subject Code']])
            ->sortable()
            ->creationRules('required', 'max:255', 'unique:subjects,code')
            ->updateRules('required', 'max:255')
            ,

        Textarea::make('Description')
            ->nullable(),

        BelongsToMany::make('Teachers'),




    ];
}

Метод полей в TeacherРесурс

 public function fields(Request $request)
{
    return [
        ID::make()->sortable(),

        BelongsTo::make('User')
            ->searchable(),

        Text::make('First Name', 'first_name')
            ->withMeta(['extraAttributes' => ['placeholder' => 'First Name']])
            ->sortable()
            ->rules('required', 'max:50'),

        Text::make('Middle Name', 'middle_name')
            ->withMeta(['extraAttributes' => ['placeholder' => 'Middle Name']])
            ->sortable()
            ->nullable()
            ->rules('max:50'),

        Text::make('Last Name', 'last_name')
            ->withMeta(['extraAttributes' => ['placeholder' => 'Last Name']])
            ->sortable()
            ->rules('required', 'max:50'),

        Text::make('Teacher Code', 'teacher_code')
            ->withMeta(['exraAttributes' => [ 'placeholder' => 'Teacher Code']])
            ->sortable()
            ->creationRules('required', 'max:50', 'unique:teachers,teacher_code')
            ->updateRules('required', 'max:50'),

        BelongsToMany::make('Subjects'),
    ];
}

enter image description here

Любое предложение о том, как я могу заставить его работать или лучшее решение, буду очень признателен

1 Ответ

0 голосов
/ 06 ноября 2019

Без пользовательского инструмента сборки используйте следующий метод:

// app\Nova\SubjectAllocation.php
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            // SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),
            SearchableSelect::make('Teacher', 'teacher_id')->resource(\App\Nova\Teacher::class)
            ->displayUsingLabels(),

            AttachMany::make('Subjects','subject_id')
                ->showCounts()
                ->help('<b>Tip: </b> Select subjects to be allocated to the teacher')
                ->fillUsing(function($request, $model, $attribute, $requestAttribute) { 
                    $a = json_decode($request->subject_id, true);
                    $teacher = \App\Teacher::find($request->teacher_id);
                    if(count($a)==0){
                        // Error processing because no subject is choosen
                    }else if(count($a)==1){
                        $model['subject_id'] = $a[0];
                    }else{
                        $model['subject_id'] = $a[0];
                        array_shift ($a); // Remove $a[0] in $a
                        $teacher->subjects()->sync(
                            $a
                        );
                    }
                })
        ];
    }
...