121*_*21c 2 php mysql eloquent laravel-5
我有一个保存方法,我在那里进行验证,创建模型并保存.稍后在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();
});
}
Run Code Online (Sandbox Code Playgroud)
保存方法:
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
}
Run Code Online (Sandbox Code Playgroud)
在MySQL中,ID被设置(只是一个自动递增的无符号整数) - 看起来它在savePost方法完成后被设置.
我认为在$post->save()完成后,模型的ID将被设置 - 但似乎并非如此.如何从我所用的相同方法访问模型的ID save()?或者我在某个地方犯了错误?
Laravel Framework版本是5.3.26
编辑:只是为了澄清:模型(包括自动递增PK)存储在MySQL中,我只是无法以我保存的相同方法访问模型的id.
弄清楚了:
从字符串PK切换到自动递增unsigned int时遇到了这个问题.
我仍然public $incrementing = false;在Post模型中解释了这个问题.切换到$incrementing = true解决了问题.