SQLSTATE[23000]:违反完整性约束:1048 列“property_id”在 Laravel 5.2 中不能为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42659183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:30:20  来源:igfitidea点击:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'property_id' cannot be null in Laravel 5.2

phpmysqllaravellaravel-5laravel-5.2

提问by Edward Palen

I am trying to solve this problem, where I try to edit multiple files with the update method in laravel 5.2.

我正在尝试解决这个问题,我尝试在 laravel 5.2 中使用 update 方法编辑多个文件。

When I run my process and save it returns the following error:

当我运行我的进程并保存它时,会返回以下错误:

QueryException in Connection.php line 729:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'property_id' cannot be null (SQL: insert into `files` (`name`, `property_id`, `updated_at`, `created_at`) values (58bf2825d39d9.jpg, , 2017-03-07 17:37:41, 2017-03-07 17:37:41))

This is my Promperties Migration Table and your relationships

这是我的属性迁移表和你的关系

<?php

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

class CreatePropertiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('properties', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
            $table->integer('term_id')->unsigned();
            $table->foreign('term_id')
                  ->references('id')
                  ->on('terms')
                  ->onDelete('cascade');
            $table->string('address');
            $table->integer('province_id')->unsigned();
            $table->foreign('province_id')
                  ->references('id')
                  ->on('provinces')
                  ->onDelete('cascade');
            $table->string('ctime');//Tiempo de construcción de la propiedad (a?os).
            $table->string('mconstruction');//Metros de construcción (Mt2).
            $table->string('ground');//Metros de terreno (Mt2).
            $table->string('level');//Nivel/Piso.
            $table->string('elevator');//Asscensores.
            $table->string('price');
            $table->integer('currency_id')->unsigned();            
            $table->foreign('currency_id')
                  ->references('id')
                  ->on('currencies')
                  ->onDelete('cascade');
            $table->integer('client_id')->unsigned();            
            $table->foreign('client_id')
                  ->references('id')
                  ->on('clients')
                  ->onDelete('cascade');
            $table->softDeletes();
            $table->timestamps();
        });

        DB::update("ALTER TABLE properties AUTO_INCREMENT = 1000;");
    }

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

This is my File Migration Table and your relationships

这是我的文件迁移表和你的关系

<?php

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

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('property_id')->unsigned();
            $table->foreign('property_id')
                  ->references('id')
                  ->on('properties')
                  ->onDelete('cascade');
            $table->timestamps();
        });
    }

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

This is My Properties Model

这是我的属性模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Property extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $table = 'properties';

    protected $fillable = ['category_id', 'term_id', 'address', 'ctime', 'mconstruction', 'ground', 'level', 'elevator', 'price', 'currency_id', 'province_id', 'client_id'];

    // Relation with Category
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    // Relation with Term
    public function term()
    {
        return $this->belongsTo('App\Term');
    }

    // Relation with Province
    public function province()
    {
        return $this->belongsTo('App\Province');
    }

    // Relation with Client
    public function client()
    {
        return $this->belongsTo('App\Client', 'client_id');
    }

    // Relation with Currency
    public function currency()
    {
        return $this->belongsTo('App\Currency');
    }

    // Relation with Municipality
    public function municipality()
    {
        return $this->belongsTo('App\Municipality');
    }

    // Relation with File
    public function files()
    {
        return $this->hasMany('App\File');
    }

    public function scopeSearch($query, $search) {
        return $query
            ->where('category_id', 'like', "%" . $search . "%")            
            ->orWhere('address', 'like', "%" . $search . "%")
            ->orWhere('price', 'like', "%" . $search . "%");
    }
}

This is My Files Model

这是我的文件模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class File extends Model
{
    protected $table = 'files';

    protected $fillable = ['name', 'property_id'];

    // Relation with Property
    public function property()
    {
        return $this->belongsTo('App\Property');
    }
}

And here I show part of my controller where the problem is

在这里,我展示了我的控制器的一部分问题所在

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Intervention\Image\Exception\NotReadableException;

use Illuminate\Support\Facades\Input;

use App\Http\Requests;
use App\Client;
use App\Category;
use App\Term;
use App\Province;
use App\Municipality;
use App\Property;
use App\Currency;
use App\User;
use App\File;
use Image;
use View;

class PropertyController extends Controller
{    
    public function update(Request $request, $id)
    {
        //dd($request->input());

        $updated = Property::findorFail($id);

        $properties = $request->all();

        $property_id = $request->get('property_id');

        $updated->fill($properties)->save();

        // -- Images update method -- //

        $images = $request->file('avatar'); 

        foreach ($images as $image) 
        {
            $rules = array(
                'avatar' => 'required|mimes:png,gif,jpeg,jpg|max:20000'
            );

            $validator = \Validator::make(array('avatar'=> $image), $rules);

            if (! $validator->passes())
            {
                return redirect()->back()->withErrors($validator);
            }

            $extension = $image->getClientOriginalExtension();
            $filename = uniqid() . '.' . $extension;
            $path = public_path() . 'uploads/products/';

            //dd($extension);

            Image::make($image)->resize(300, 200)->save( public_path('uploads/products/' . $filename ) );

            //Move file into uploads folder 
            $image->move($path, $filename);
            //Insert file name in db

            //dd($image);

            $image = File::create([ 
                'name'        => $filename,
                'property_id' => $property_id
            ]);

        }

        // -- End method -- //

        return redirect()->route('properties.index')
                         ->with('success','Propiedad actualizada satisfactoriamente!!!');
    }

This is a test before the $ image = File :: create method, returns the following values:

这是在 $image = File::create 方法之前的一个测试,返回以下值:

enter image description here

在此处输入图片说明

What I try to do is replace the files and delete them so they do not accumulate in the directory that stores these images.

我尝试做的是替换文件并删除它们,这样它们就不会堆积在存储这些图像的目录中。

回答by Carlos Adames

You need to verify that your property_id is been sent in your form request. Add it as hidden field in case you missed to add it.

您需要验证您的 property_id 是否已在您的表单请求中发送。如果您错过添加它,请将其添加为隐藏字段。

  <Input  type="hidden"  name="property_id" value="{{$properties->id}}" >

回答by Joe

The error you're seeing is because the the column property_idon the filestable is not nullable.

您看到的错误是因为表property_id上的列files不可为空。

if you want this column to accept null values you will need to allow this in your migration:

如果您希望此列接受空值,则需要在迁移中允许:

 $table->integer('property_id')->unsigned()->nullable();

Of course you probably don't want that value to be null, so...

当然,您可能不希望该值为空,所以...

 $property_id = $request->get('property_id');

Are you sure that the $property_idvariable is being populated in the line above? Should it not be:

您确定$property_id在上面的行中填充了变量吗?不应该是:

$property_id = $request->input('property_id');