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

时间:2015-07-20 23:10:51

标签: php laravel laravel-4

我对与问题相关的评论有一个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')));
        }           
    }
}

3 个答案:

答案 0 :(得分:4)

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

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

if($comment) {
    // Comment was saved

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

答案 1 :(得分:1)

我认为你可以通过$comment->id来引用它。你有没试过这个?

答案 2 :(得分:1)

通常$comment->id应该有效,但您可以尝试获取插入的ID,而不应该是save之后的注释:

DB::getPdo()->lastInsertId();