如果我按如下所示插入新行:
$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
答案 0 :(得分:0)
您可以使用创建的帖子对象,因为保存后,帖子具有唯一的ID:
$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = $post->id;
希望有帮助。
答案 1 :(得分:0)
如果$post->id
还不存在,您可以尝试一下
$post = new Post();
$post->save();
$post = $post->fresh();
$talk = new Talk();
$talk->post_id = $post->id;
答案 2 :(得分:0)
您也可以执行此操作。使用Post::latest()->get()->take(1)->pluck('id');
获取最新添加的内容。
例如以下示例:
$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = Post::latest()->get()->take(1)->pluck('id');