簡體   English   中英

SQLSTATE [HY000]:常規錯誤:1364字段“ starting_balance”沒有默認值

[英]SQLSTATE[HY000]: General error: 1364 Field 'starting_balance' doesn't have a default value

我收到一個非常奇怪的“字段沒有默認值”錯誤。 有問題的字段是starting_balance 看來Laravel試圖將starting_balance字段保存為數據庫,好像它是空的,但我確定不是。 任何幫助表示贊賞。

我嘗試為遷移中的字段添加默認值,但這仍然無濟於事。

這是我對該模型的遷移:

<?php

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

class CreateApartmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('apartments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('entrance_id');
            $table->integer('user_id')->nullable()->default(null);
            $table->integer('floor');
            $table->integer('apt_number');
            $table->string('square_meters', 64)->nullable();
            $table->decimal('percent_ideal_parts', 10, 3)->nullable();
            $table->decimal('starting_balance', 8, 2);
            $table->string('animals', 200)->nullable();
            $table->string('other_information', 2048)->nullable();
            $table->timestamps();
        });
    }

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

這是處理請求的控制器中的相關部分:

public function store(Request $request, ApartmentRequest $apartmentRequest)
{
    $apartment = new Apartment($request->except(['obekt_id', '_token']));

    if ($apartment->save())
    {
        Session::flash('success', 'Апартамента беше запазен успешно.');
        return redirect('/entrances/' . $apartment->entrance->id . '/apartments');
    }
    else
    {
        Session::flash('error', 'Имаше проблем докато запазвахме апартамента.');
        return back();
    }
}

這是我的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Apartment extends Model
{
    protected $fillable = ['entrance_id', 'user_id', 'floor', 'apt_number', 'square_meters', 'percent_ideal_parts', 'starting_balance', 'animals', 'other_information'];

    public function people()
    {
        return $this->hasMany('App\Person');
    }

    public function entrance()
    {
        return $this->belongsTo('App\Entrance');
    }

    public function taksiDomoupravitel()
    {
        return $this->hasMany('App\TaksaDomoupravitel');
    }

    public function taksiFro()
    {
        return $this->hasMany('App\TaksaFro');
    }

    public function payments()
    {
        return $this->hasMany('App\Payment');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

這是$ request-> except('obekt_id','_token')部分的dd:

array:9 [▼
  "entrance_id" => "1"
  "user_id" => null
  "floor" => "15"
  "apt_number" => "15"
  "square_meters" => null
  "percent_ideal_parts" => "15"
  "starting_balance" => "-20"
  "animals" => null
  "other_information" => null
]

這是我的ApartmentRequest驗證類:

<?php

namespace App\Http\Requests;

use App\Rules\UniqueFloorAndAptNumber;
use Illuminate\Foundation\Http\FormRequest;

class ApartmentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'obekt_id' => 'required|exists:obekti,id',
            'entrance_id' => 'required|exists:entrances,id',
            'user_id' => 'exists:users,id|nullable',
            'floor' => ['required', 'numeric', new UniqueFloorAndAptNumber],
            'apt_number' => ['required', 'numeric', new UniqueFloorAndAptNumber],
            'percent_ideal_parts' => 'required|numeric',
            'starting_balance' => 'required|numeric',
            'animals' => 'max:200',
            'other_information' => 'max:2048',
        ];
    }
}

這是起始余額字段的刀片視圖部分:

<div class="form-group{{ $errors->has('starting_balance') ? ' has-error' : '' }}">
    <label for="starting_balance" class="col-md-4 control-label red-text">Моля въведете начално салдо *</label>

    <div class="col-md-6">
        <input id="starting_balance" type="text" class="form-control" name="starting_balance" value="{{ old('starting_balance') }}">

        @if ($errors->has('starting_balance'))
            <span class="help-block">
                <strong>{{ $errors->first('starting_balance') }}</strong>
            </span>
        @endif
    </div>
</div>

錯誤非常明顯: starting_balance沒有默認值。

您可以通過添加默認值來更新遷移文件,如下所示:

// if you want to set 0 as default value
$table->decimal('starting_balance', 8, 2)->default(0);

// if you want to set NULL as default value
$table->decimal('starting_balance', 8, 2)->nullable();

好的,我遇到了您的問題,您驗證了ApartmentRequest $ apartmentRequest但使用了Request $ request您的代碼應如下所示

public function store(ApartmentRequest $apartmentRequest)
{
    $apartment = new Apartment($apartmentRequest->except(['obekt_id', '_token']));

    if ($apartment->save())
    {
        Session::flash('success', 'Апартамента беше запазен успешно.');
        return redirect('/entrances/' . $apartment->entrance->id . '/apartments');
    }
    else
    {
        Session::flash('error', 'Имаше проблем докато запазвахме апартамента.');
        return back();
    }
}

嘗試這個:

$apartment -> starting_balance = $request -> starting_balance;

后:

$apartment = new Apartment($request->except(['obekt_id', '_token']));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM