php 保存后Laravel型号ID为空(ID递增)

14ifxucb  于 2023-03-16  发布在  PHP
关注(0)|答案(2)|浏览(164)

我有一个保存方法,我在其中进行验证,创建一个模型并保存它。稍后在save方法中,我尝试访问模型的ID,它是NULL。
模式:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        //and other fields that aren't important right now
        $table->timestamps();
    });
}

保存方法:

public function savePost(Request $request) {

    $this->validate($request, [
        //some validation happens here
    ]);

    $post = new Post();
    $title = $request->input('title');
    $body = $request->input('body');

    $post->title = $title;
    $post->body = $body;

    $post->save();

    //I later try to access the $post->id here and it's still NULL.
    var_dump($post->id);//NULL
}

在MySQL中,ID是被设置的(只是一个自动递增的无符号整数)-看起来它是在savePost方法完成后设置的。
我原以为$post->save()完成后,模型的ID会被设置--但事实似乎并非如此。我如何从save()的相同方法访问模型的ID?或者我在哪里犯了错误?
Laravel框架版本为5.3.26
编辑:只是为了澄清:模型(包括自动递增的PK)被存储在MySQL中,我只是无法以保存它的相同方法访问模型的ID。

sczxawaw

sczxawaw1#

我想明白了:
我在从字符串PK切换到自动递增的unsigned int时遇到了这个问题。
我在Post模型中还有public $incrementing = false;,这就解释了这个问题,切换到$incrementing = true解决了这个问题。

vnzz0bqm

vnzz0bqm2#

对于其他使用Pivot/Junction表的开发人员来说,如果您的模型扩展的是Pivot而不是Model,那么这就是原因。
正如@noob提到的,您必须手动启用public $incrementing = true;,或者只是扩展Model

相关问题