【发布时间】:2017-01-15 05:24:33
【问题描述】:
我有一个保存方法,用于验证、创建模型并保存它。稍后在保存方法中,我尝试访问模型的 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。
【问题讨论】:
标签: php mysql laravel-5 eloquent