2015-07-20 28 views
2

对于与问题相关的注释,我有一个morphMany关系模型我想知道如何在保存新注释模型时获取新插入的ID。Laravel从保存的关系中获取新插入的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

保存的评论记录将保存返回上:

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

if($comment) { 
    // Comment was saved 

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

是的,我试过了,当我把它放在我的Response :: json – ONYX

+0

中时,它给了我未定义的内容,我只是现在就测试了它并按预期工作。你的评论模型中是否有主键?您也可以尝试'$ comment-> getKey()'来检索模型主键。 –

1

我认为你可以参考它只是通过做$comment->id。你有没有试过这个?

+0

展我看看它的一些示例代码。我试过了,当我把它放入我的ajax响应中时,我得到了未定义的响应:: json(array('id'=> $ comment-> id)); – ONYX

+0

@KDM我会尝试'dd($ comment-> id)'。如果它返回一个数字而不是null,那么问题在于别处。让我知道会发生什么,所以我可以继续尝试和帮助 – noahdotgansallo

1

通常$comment->id应该工作,但你可以尝试让插入的ID而不是这应该是评论的后save

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