SQLSTATE [23000]: нарушение ограничения целостности: 1048 Столбец 'giorno_raccolta_id' не может быть пустым

Календарь

Я разрабатываю приложение с Laravel 8, чтобы показать еженедельный календарь раздельного сбора отходов, но когда я нажимаю кнопку добавления дня, у меня появляется следующая ошибка: SQLSTATE [23000]: нарушение ограничения целостности: 1048 Столбец 'giorno_raccolta_id' не может быть нулевым (SQL: вставить в значения notes ( collection_day_id, _3 _, _ 4_, _5 _, _ 6_) (?,?,?, 2021-05-28 12:48:04, 2021-05-28 12:48:04))

  1. Form.blade.php

         <div class="input-group mb-3">
         <label class="input-group-text" for="inputGroupSelect01">Giorno</label>
        <select name="giorno" class="form-select" id="inputGroupSelect01">
       @foreach ($days as $day)
        <option value="{{$day->id}}" {{$note->giorno_id == $day->id ? 'selected' : ''}} >{{$day->giorno}}</option>
      @endforeach
    </select>
    </div>
    
     @if($errors->has('giorno'))
      <div class="alert alert-danger" role="alert">
       {{ $errors->first('giorno')}}
      </div>
     @endif
    
      <div class="input-group mb-3">
      <label class="input-group-text" for="inputGroupSelect01">Tipologia</label>
      <select name="tipologia" class="form-select" id="inputGroupSelect01">
       @foreach ($categories as $c)
         <option value="{{$c->id}}" {{$note->tipologia_id == $c->id ? 'selected' : ''}} >{{$c->categoria}}</option>
       @endforeach
     </select>
     </div>
    
    @if($errors->has('tipologia'))
      <div class="alert alert-danger" role="alert">
     {{ $errors->first('tipologia')}}
     </div>
    @endif
    
    <div class="input-group mb-3">
    <label class="input-group-text" for="inputGroupSelect01">Giorno raccolta</label>
    <select name="giorno_raccolta_id" class="form-select" id="inputGroupSelect01">
      @foreach ($days as $day)
         <option value="{{$day->id}}" {{$note->giorno_raccolta_id == $day->id ? 'selected' : ''}} >{{$day->giorno}}</option>
      @endforeach
    </select>
    </div>
    
      @if($errors->has('giorno_raccolta_id'))
     <div class="alert alert-danger" role="alert">
        {{ $errors->first('giorno_raccolta_id')}}
     </div>
     @endif
    
     <div class="input-group mb-3">
       <label class="input-group-text">Ora inizio</label>
       <input type="time" name="ora_inizio">
      </div>
    
      @if($errors->has('ora_inizio'))
        <div class="alert alert-danger" role="alert">
          {{ $errors->first('ora_inizio')}}
        </div>
      @endif
    
      <div class="input-group mb-3">
        <label class="input-group-text">Ora fine</label>
        <input type="time" name="ora_fine">
      </div>
    
      @if($errors->has('ora_fine'))
        <div class="alert alert-danger" role="alert">
         {{ $errors->first('ora_fine')}}
       </div>
      @endif
    
     @csrf
    

2. Примечания к таблице

          public function up()
{
    Schema::create('notes', function (Blueprint $table) {
        $table->increments('id')->start_from(1);
        $table->unsignedInteger('giorno_id');
        $table->unsignedInteger('tipologia_id');
        $table->unsignedInteger('giorno_raccolta_id');
        $table->time('ora_inizio');
        $table->time('ora_fine');
        $table->timestamps();
    });
}

3. WeekController

           <?php

              namespace App\Http\Controllers;


               use App\Models\note;
               use App\Models\Day;

               use Illuminate\Http\Request;



             class WeekController extends Controller
              {
               public function index(){
    $notes = note::all();

    return view('calendar.index',
    compact('notes'));
   
}

public function create(){
    $days = Day::all();
    $categories = Category::all();
    $notes = new note();
    
    return view('calendar.create',
    compact('days', 'categories', 'notes'));
}


public function store(){
        
        note::create($this->validateRequest());
        return redirect()->route('calendar.index');
}




public function show(note $note){
    $note = note::find($note)->first();
    return view('calendar.show',compact('note'));
}


public function edit(note $note){
    $days = Day::all();
    return view('calendar.edit',compact('note','days'));
}



public function update(note $note){
    $note ->update($this->validateRequest());


    return redirect()->route('calendar.show',$note->id);
}


public function destroy(note $notes){
    $notes->delete();
    return redirect()->route('calendar.index');
}


private function validateRequest(){
    return request()->validate([
        'giorno_id' => 'required|unique:notes',
        'tipologia' => 'required',
        'giorno_raccolta' => 'required',
        'ora_inizio' => 'required',
        'ora_fine' => 'required'
    ]);
}



 }

У меня также есть еще одна проблема, когда я иду сохранять данные в базе данных, ничего не сохраняется. Можете ли вы помочь мне устранить неполадки в приложении.

Дни и виды отказов я восстанавливаю по двум другим таблицам:

  1. Таблица дней

          public function up()
        {
           Schema::create('days', function (Blueprint $table) {
             $table->id();
             $table->string('giorno');
             $table->timestamps();
          });
        }
    

2. Таблица категорий

      public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('categoria');
        $table->timestamps();
    });
}

Модель Note

       <?php

           namespace App\Models;

           use Illuminate\Database\Eloquent\Factories\HasFactory;
           use Illuminate\Database\Eloquent\Model;
           use App\Models\Day;



          class note extends Model
         {
           use HasFactory;

            protected $fillable = [];
            protected $guarded = ['id'];


            public function days(){
            return $this->hasOne(Day::class);
           }
         }

Дневная модель

      <?php

         namespace App\Models;

          use Illuminate\Database\Eloquent\Factories\HasFactory;
          use Illuminate\Database\Eloquent\Model;
          use App\Models\note;
          use App\Models\Category;

          class Day extends Model
    {
         use HasFactory;


        public function notes(){
          return $this->hasOne(note::class);
    }

       public function category(){
      return $this->belongsTo(category::class);
     }
   }

Категория модели

        <?php

         namespace App\Models;

        use Illuminate\Database\Eloquent\Factories\HasFactory;
        use Illuminate\Database\Eloquent\Model;
        use App\Model\Day;

        class Category extends Model
       {
         use HasFactory;

        public function days(){
        return $this->hasMany(Day::class);
       }

      }

person Piero Sabino    schedule 28.05.2021    source источник
comment
Вы реализуете заполняемую или охраняемую модель в Note ???   -  person Prospero    schedule 29.05.2021
comment
Да, реализую заполняемый   -  person Piero Sabino    schedule 29.05.2021


Ответы (1)


Я предлагаю вам сделать $ fillable и передать ему атрибуты, которые вы хотите сделать массово назначаемыми https://laravel.com/docs/8.x/eloquent#mass-assignment. С другой стороны, я вижу, что все ваши элементы select имеют одинаковый идентификатор, поскольку элемент идентификатора DOM должен быть уникальным. И, наконец, проверьте в методе create данные, полученные $ request.

....(Request $request)
{
   dd($request)
}
person Prospero    schedule 29.05.2021
comment
Теперь у меня возникла следующая проблема: SQLSTATE [42S22]: Столбец не найден: 1054 Неизвестный столбец 'days.note_id' в 'where clause' (SQL: выберите * из days, где _2 _._ 3_ = 1 и _4 _._ 5_ не является нулевым пределом 1) (Просмотр: C: \ Users \ Piero \ Desktop \ Prova \ recycle \ resources \ views \ calendar \ index.blade.php) - person Piero Sabino; 30.05.2021
comment
Проверьте связь "один-один" между Notes и Days, это неверно. laravel.com/docs/8.x/eloquent-relationships# индивидуально - person Prospero; 31.05.2021
comment
У меня две проблемы: первая - я не могу добавить и сохранить данные в базе данных; второй я хотел бы получить название дня, день сбора и тип отходов. - person Piero Sabino; 31.05.2021