gpt4 book ai didi

php - Laravel 在保存时从关系中获取新插入的 id

转载 作者:行者123 更新时间:2023-12-03 04:46:30 25 4
gpt4 key购买 nike

我对与问题模型相关的评论有 morphMany 关系,我想知道在保存新评论模型时如何获取新插入的 id。

    public function postComment() {

if(Request::ajax() && Auth::check()) {
//Input::merge(array_map('trim', Input::all()));

$comment = new Comment;
$comment->user_id = Auth::user()->id;
$comment->body = Helper::strip_tags(Input::get('body'));
$question_id = Input::get('question_id');
$question = Question::find($question_id);

// here in the if statement how do I get the newly created id of a comment
if($question->comments()->save($comment)) {

return Response::json(array('success' => true, 'body' => Input::get('body'),
'userlink' => HTML::linkRoute('profile', Auth::user()->username, array('id' => Auth::user()->id)), 'date' => date("F j, Y, g:i a") ));
} else {
return Response::json(array('success' => false, 'body' => Input::get('body')));
}
}
}

最佳答案

保存时将返回已保存的评论记录:

$comment = $question->comments()->save($comment);

if($comment) {
// Comment was saved

$comment->id;
} else {
// Comment was not saved
}

关于php - Laravel 在保存时从关系中获取新插入的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com