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

ONY*_*NYX 5 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')));
        }           
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*man 6

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

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

if($comment) {
    // Comment was saved

    $comment->id;
} else {
    // Comment was not saved
}
Run Code Online (Sandbox Code Playgroud)