简体   繁体   English

Laravel:违反完整性约束

[英]Laravel: Integrity constraint violation

I'm studying some Laravel and at some point I had to re-migrate the database because I had to change a table. 我正在研究一些Laravel,在某个时候我不得不重新迁移数据库,因为必须更改表。 I'm using postman to do testing, and one of the api methods give me the error: 我使用邮递员进行测试,其中一种api方法给我错误:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: events.user_id (SQL: insert into "events" ("sport", "title", "players", "when", "description", "location", "updated_at", "created_at") values (Hockey, Grass Hockey, 12, 30/09/2018, Come join us, Fairview park, 2018-11-08 22:19:45, 2018-11-08 22:19:45)) SQLSTATE [23000]:违反完整性约束:19 NOT NULL约束失败:events.user_id(SQL:插入“事件”(“ sport”,“ title”,“ players”,“ when”,“ description”,“ location” ,“ updated_at”,“ created_at”)值(曲棍球,草地曲棍球,2018年10月30日,快来加入我们,锦绣花园,2018-11-08 22:19:45,2018-11-08 22:19 :45))

so it seems to be a problem with the events.user_id which I changed on a table called Events to have a relationship with the Users table. 因此,events.user_id似乎存在问题,我在名为Events的表上进行了更改,使其与Users表具有关系。 Some examples I found by researching is on table fields that were not ids, so I don't how to figure this one out, maybe some of you can help me! 我通过研究发现的一些示例是关于非id的表字段的,所以我不知道如何解决这一问题,也许有些人可以帮助我!

here are the migrations for Events and Users: 这是事件和用户的迁移:

 public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
            $table->string('sport');
            $table->string('title');
            $table->decimal('players', 8, 2);
            $table->date('when');
            $table->mediumText('description');
            $table->string('location');
            $table->timestamps();
        });
    }


public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Here are the models: 这些是模型:

class Event extends Model
{
    protected $fillable = [
        'sport',
        'title',
        'players',
        'when',
        'description',
        'location'
    ];

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

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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

And below is the api method that is giving me the error: 下面是给我错误的api方法:

Route::post('/admin/create-event', function (Request $request) {
    $data = $request->all();

    $event = Event::create(
        [
            'sport' => $data['sport'],
            'title' => $data['title'],
            'players' => $data['players'],
            'when' => $data['when'],
            'description' => $data['description'],
            'location' => $data['location'],
        ]
    );

    return $event;
});

Thanks guys! 多谢你们!

Edit: 编辑:

Route::middleware('auth:api')->post('/admin/create-event', function (Request $request) {
    $user = $request->user();
    $data = $request->all();

    $event = Event::create(
        [
            'user_id' => \Auth::user()->id,
            'sport' => $data['sport'],
            'title' => $data['title'],
            'players' => $data['players'],
            'when' => $data['when'],
            'description' => $data['description'],
            'location' => $data['location'],
        ]
    );

    return $event;
});

You need to pass the user_id: 您需要传递user_id:

'user_id' => \Auth::user()->id

The example above requires an authenticated user in the session, but if you are making the request using postman you probably don't have one. 上面的示例在会话中需要经过身份验证的用户,但是如果您使用邮递员发出请求,则可能没有人。

Anyway, you need to provide the user_id that will be stored in the database. 无论如何,您需要提供将存储在数据库中的user_id。

EDIT 编辑

Eloquent's method create will copy to the model only the attributes defined as fillable . Eloquent的方法create只会将定义为fillable的属性复制到模型。 So you have two options: 因此,您有两种选择:

  • Add user_id to $fillable user_id添加到$fillable
  • Use newInstance instead of create , manually set the user_id with $event->user_id = ... , and manually save the $event model with $event->save(); 使用newInstance代替create ,使用$event->user_id = ...手动设置user_id ,并使用$event->save();手动保存$event模型$event->save();

I think you have to add 'user_id' to $fillable of Event class: 我认为您必须将'user_id'添加到Event类的$ fillable中:

class Event extends Model
{
    protected $fillable = [
         'sport',
         'title',
         'players',
         'when',
         'description',
         'location',
         'user_id'
     ];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM