我有一个保存方法,在其中进行验证、创建模型并保存。稍后在保存方法中,我尝试访问模型的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会被设定,但事实并非如此。我该如何在同一方法中访问模型的ID,而我又对它进行了“save()”操作?或者我在哪里犯了错误?
Laravel框架版本为5.3.26。
编辑:澄清一下:模型(包括自动递增的主键)被存储在MySQL中,只是我无法在保存它的同一方法中访问模型的ID。