首页 > 解决方案 > 在控制器中传递新创建行的 ID

问题描述

如果我插入了一个新行,如下所示:

$post = new Post();
$post->save();

有没有一种直接的方法来调用上面刚刚创建的 post_id 并将其插入另一个表的新行中(而不是更改许多东西以从视图中传递它)?

$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = // I need to put here the post_id just created. Both inserts 
                //are in the same controller/method

标签: phplaravel

解决方案


如果$post->id还没有,你可以试试这个

$post = new Post();
$post->save();
$post = $post->fresh();

$talk = new Talk();
$talk->post_id = $post->id;

推荐阅读