为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
弑天下 2023-11-05 15:53:37
我正在使用 laravel 6。我创建了一个名为 的表'student',其中列的值增量'id'应该发生,但没有发生。这是我的迁移文件:<?phpuse 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');    }}在我的学生表中:
查看完整描述

3 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

您所使用的数据库有可能是students手动(不是通过迁移,而是通过执行未设置自动增量的 SQL 查询)或在应用迁移之后为表设置了架构的数据库,自动增量已被删除。

因为您的迁移代码是根据该方法的官方 Laravel 文档increments(string $attribute)正确编写的:

https://img1.sycdn.imooc.com/6559d69800019d0f05000221.jpgz

我在这里看到两个解决方案:

  1. 通过 SQL 查询更改表列,使其与迁移中的描述匹配

ALTER TABLE students CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY;

或使用 phpmyadmin 或 IDE 工具进行相同操作;

  1. 使用迁移 ( ) 生成模式php artisan migrate --path=database/migrations/..._create_students_table.php,但为此,您首先需要保存学生表数据,例如保存到转储。

由于您使用的是phpmyadminid ,请查看表中属性的设置students


查看完整回答
反对 回复 2023-11-05
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

根据您的控制器代码判断,我认为错误位于您获取学生模型实例的行中的某个位置


改变


 $student = new Student;


  $student = new Student();

您需要特定模型的新实例才能插入新 ID,也请发布您当前的模型代码。


示例模型代码。


<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;


class Product extends Model

{

    use SoftDeletes;


    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'product_bar_code', 'product_name', 'product_image', 'product_price'

    ];


    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    protected $hidden = ['created_at', 'updated_at', 'deleted_at'];

}

也许您编写模型代码的方式有问题。


查看完整回答
反对 回复 2023-11-05
?
慕斯王

TA贡献1864条经验 获得超2个赞

我能想到的唯一原因是如果你在模型中做了这样的事情:


    /**

     * Indicates if the IDs are auto-incrementing.

     *

     * @var bool

     */

    public $incrementing = false;

如果是这样,则应将其设置为 true 或完全删除。


其次,确保您的id模型受到保护,如下所示:


/**

 * The attributes that aren't mass assignable.

 *

 * @var array

 */

protected $guarded = ['id'];

这样您就可以避免大量分配。


查看完整回答
反对 回复 2023-11-05
  • 3 回答
  • 0 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信