保存后,Laravel模型ID为null(ID递增)

时间:2017-01-15 05:24:33

标签: php mysql laravel-5 eloquent

我有一个保存方法,我在其中进行验证,创建模型并保存。稍后在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 Framework版本为5.3.26

编辑:只是为了澄清:模型(包括自动递增PK)存储在MySQL中,我只是无法以我保存的相同方法访问模型的ID。

2 个答案:

答案 0 :(得分:5)

想出来:

我在从字符串PK切换到自动递增unsigned int时遇到了这个问题。

public $incrementing = false;模型中我仍然有Post,这解释了这个问题。切换到$incrementing = true解决了问题。

答案 1 :(得分:0)

对于其他人如何使用枢轴/连接表,因此,如果您的模型扩展 Pivot 而不是 Model 那么这就是原因,

正如@noob 提到的,您必须手动启用 public $incrementing = true; 或仅扩展 Model