При сохранении новой записи базы данных с помощью операций сохранения / создания контроллера возвращается SQLSTATE [HY000]: общая ошибка: 1364 - PullRequest
0 голосов
/ 26 апреля 2019

При попытке сохранить запись в моей базе данных с помощью Eloquent ORM я получаю сообщение об ошибке,

Illuminate\Database\QueryException thrown with message "SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `animals` (`updated_at`, `created_at`) values (2019-04-25 22:35:47, 2019-04-25 22:35:47))"

Однако в моих миграциях я никогда не указываю имя как имя по умолчанию, как это требуется.

Мой класс AnimalsController.

  public function create()
    {
        return view('animals.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $animal = Animal::create([
          $request->input()
        ]);

        // $animal = new Animal;
        // $animal->name = $request->name;
        // $animal->dob = $request->dob;
        // $animal->description =  $request->description;
        // $animal->image = $request->image;
        // $animal->available = $request->available;
        //
        // echo $request->id;
        // echo "test";
        // echo $animal->id;

        // flash('Animal Added')->success();

        return redirect()->route('animals.show')->with('animal', $animal);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Animal  $animal
     * @return \Illuminate\Http\Response
     */
    public function show(Animal $animal)
    {
        return view('animals.show')->with('animal', $animal);
    }

Animal.php

class Animal extends Model
{

  use SoftDeletes;

  protected $dates = [
    'created_at',
    'updated_at'
  ];

  /**
   * Set the Attributes which are alllowed
   * to be assigned
   */
  protected $fillable = [
    'name',
    'dob',
    'description',
    'image',
    'available'
  ];

create.blade.php - Где вводятся данные формы

<div class="row">
  <div class="col">
    {!! Form::open(['route' => 'animals.store'], ['class' => 'form', 'files' => true]) !!}

    <div class="form-group">
      {!! Form::label('name', 'Animal Name', ['class' => 'control-label']) !!}
      {!! Form::text('name', null, ['class' => 'form-control input-lg', 'placeholder' => 'Waffles']) !!}
    </div>

    <div class="form-group">
      {!! Form::label('dob', "DOB", ['class' => 'control-label']) !!}
      {!! Form::date('dob') !!}
    </div>

    <div class="form-group">
      {!! Form::label('description', "Description", ['class' => 'control-label']) !!}
      {!! Form::textarea('description', null, ['size' => '20x3', 'class' => 'form-control input-lg', 'placeholder' => 'Describe the animal']) !!}
    </div>

    <div class="form-group">
      {!! Form::label('image', "Image", ['class' => 'control-label']) !!}
      {!! Form::file('image') !!}
    </div>

    <div class="form-group">
      {!! Form::label('available', "Available", ['class' => 'control-label']) !!}
      {!! Form::checkbox('available', 'value') !!}
    </div>

    <div class="form-group">
      {!! Form::submit('Add Animal', ['class' => 'submit btn btn-info btn-lg', 'style' => 'width: 100%']) !!}
    </div>

    {!! Form::close() !!}

  </div>

Перенос CreateAnimalsTable

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAnimalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('animals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 20);
            $table->date('dob');
            $table->mediumText('description');
            $table->string('image');
            $table->boolean('available')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('animals');
    }
}

И в случае, если это что-то стоит, мой файл show.blade.php.

<div class="container">
    <div class="row">
      <div class="col-xl-12 text-center">
          <p class="text-primary" style="margin-top:100px;">{{ $animal->name }} has animal ID #{{ $animal->id }}. Date: {{ $animal->dob }}</p>
      </div>
    </div>
</div>

Я часами играл, пытаясь заставить это работать, и я до боли слеп к решению.

Я, вероятно, должен также упомянуть, что если я использую этот код

public function store(Request $request)
    {
        // $animal = Animal::create([
        //   $request->input()
        // ]);

        $animal = new Animal;
        $animal->name = $request->name;
        $animal->dob = $request->dob;
        $animal->description =  $request->description;
        $animal->image = $request->image;
        $animal->available = $request->available;

        echo $request->id;
        echo "test";
        echo $animal->id;

        // flash('Animal Added')->success();

        return redirect()->route('animals.show')->with('animal', $animal);
    }

Вместо этого я получаю эту ошибку.

Illuminate\Routing\Exceptions\UrlGenerationException thrown with message "Missing required parameters for [Route: animals.show] [URI: animals/{animal}]."

Что у меня тоже не было исправлений, я использую ресурс в файле web.php

Route::resource('animals', 'AnimalsController');

Это привело меня к мысли, что $ fillable не работал должным образом, и вместо этого использовал описанный выше метод, однако он все еще не работал.

Если я сделаю Имя по умолчанию в Схеме, мне придется присвоить каждому другому атрибуту значение по умолчанию, чего я не хочу делать.

Надеюсь, я дал достаточно информации, чтобы быть полезной, спасибо: D

1 Ответ

0 голосов
/ 26 апреля 2019

В этом я обнаружил две проблемы.

Во-первых, я не думаю, что это сработает

$animal = Animal::create([
    $request->input()
]);

Это массив, заключенный в другой массив.Вместо этого давайте напишем:

$animal = Animal::create($request->input());

Или:

$animal = Animal::create($request->all());

Во втором примере, я думаю, что животное создано, но перенаправленный маршрут не указан правильно:

return redirect()->route('animals.show')->with('animal', $animal);

Допустим,

return redirect()->route('animals.show', $animal->id);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...