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

Php Laravel在保存时从关系中获取新插入的id,php,laravel,laravel-4,Php,Laravel,Laravel 4,对于与问题模型相关的注释,我有很多关系。我想知道在保存新注释模型时,如何获取新插入的id public function postComment() { if(Request::ajax() && Auth::check()) { //Input::merge(array_map('trim', Input::all())); $comment = new Comment; $comment->user_i

对于与问题模型相关的注释,我有很多关系。我想知道在保存新注释模型时,如何获取新插入的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->id
即可引用它。您已经试过了吗?

保存时将返回保存的注释记录:

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

if($comment) {
    // Comment was saved

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

通常,
$comment->id
应该可以工作,但是您可以尝试获取插入的id,该id应该是
保存后的注释:

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

给我看一些示例代码,看看它应该是什么样子。我尝试了它,但当我把它放在ajax响应::json(array('id'=>$comment->id))中时,我没有定义它@KDM我会尝试
dd($comment->id)
。如果它返回一个数字而不是null,那么问题就出在其他地方。让我知道发生了什么,这样我可以继续尝试和帮助是的,我试过了,当我把它放在我的响应中时,它给了我未定义的东西::jsonI现在刚刚测试了这个,并按预期工作。您的评论模型上有主键吗?您还可以尝试
$comment->getKey()
检索模型主键。