为什么数据库的“id”列的值显示为空?

我正在使用 laravel 6。我创建了一个名为 的表'student',其中列的值增量'id'应该发生,但没有发生。


这是我的迁移文件:


<?php


use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;


class CreateStudentsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('students', function (Blueprint $table) {

            $table->increments('id');

            $table->string('name');

            $table->string('email');

            $table->bigInteger('phone');

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('students');

    }

}


在我的学生表中:

https://img1.sycdn.imooc.com/65474a150001303906520168.jpg

弑天下
浏览 182回答 3
3回答

一只萌萌小番薯

您所使用的数据库有可能是students手动(不是通过迁移,而是通过执行未设置自动增量的 SQL 查询)或在应用迁移之后为表设置了架构的数据库,自动增量已被删除。因为您的迁移代码是根据该方法的官方 Laravel 文档increments(string $attribute)正确编写的:z我在这里看到两个解决方案:通过 SQL 查询更改表列,使其与迁移中的描述匹配ALTER TABLE students CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY;或使用 phpmyadmin 或 IDE 工具进行相同操作;使用迁移 ( ) 生成模式php artisan migrate --path=database/migrations/..._create_students_table.php,但为此,您首先需要保存学生表数据,例如保存到转储。由于您使用的是phpmyadminid ,请查看表中属性的设置students。

慕虎7371278

根据您的控制器代码判断,我认为错误位于您获取学生模型实例的行中的某个位置改变&nbsp;$student = new Student;到&nbsp; $student = new Student();您需要特定模型的新实例才能插入新 ID,也请发布您当前的模型代码。示例模型代码。<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\SoftDeletes;class Product extends Model{&nbsp; &nbsp; use SoftDeletes;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The attributes that are mass assignable.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $fillable = [&nbsp; &nbsp; &nbsp; &nbsp; 'product_bar_code', 'product_name', 'product_image', 'product_price'&nbsp; &nbsp; ];&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The attributes that should be hidden for arrays.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $hidden = ['created_at', 'updated_at', 'deleted_at'];}也许您编写模型代码的方式有问题。

慕斯王

我能想到的唯一原因是如果你在模型中做了这样的事情:&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Indicates if the IDs are auto-incrementing.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var bool&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public $incrementing = false;如果是这样,则应将其设置为 true 或完全删除。其次,确保您的id模型受到保护,如下所示:/**&nbsp;* The attributes that aren't mass assignable.&nbsp;*&nbsp;* @var array&nbsp;*/protected $guarded = ['id'];这样您就可以避免大量分配。
打开App,查看更多内容
随时随地看视频慕课网APP