Laravel静态创建方法以插入记录返回空ID

时间:2020-04-26 07:28:07

标签: php mysql laravel laravel-6

我正在使用Laravel 7和Tinker CLI

我想使用静态创建方法在Profile表中插入一条记录,但它返回id列的空值(不是我提供的值,而是在数据库中自动递增)。 在下图中,我创建了一个数组->然后将其传递给创建方法->插入了记录,但 id列不可访问

Insertion done using tinker cli

我已将laravel 7的默认主键'id'更改为用户名,而未更改主键create()方法会返回正确的值,请告诉我在我的情况下它将如何给出id的值使用用户名作为主键

Record inserted with id value but returns null how access it

以id值插入的记录,但使用create()方法插入后如何访问它返回null

个人资料迁移


<?php

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

class CreateProfilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('username');
            $table->timestamps();
        });
    }

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

个人资料模型


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $guarded =[];

    protected $primaryKey='username';
    protected  $keyType='string';
    public $incrementing=false;
}

0 个答案:

没有答案