post控制器
public function comment(Post $post,Request $request)
{
try{
if(empty($request->content)){
ExceptionResult::throwException(ErrorCode::COMMENT_EMPTY);
}
$comment = new Comment();
$comment->content = $request->content;
$comment->user_id = Auth::id();
$res = $post->comments()->save($comment);
//还有种
$comment->post_id = $post->id;
$res = $comment->save();
if($res){
return Redirect::back()->with('success', '评论成功');
} else {
ExceptionResult::throwException(ErrorCode::ACTION_FAIL);
}
}catch (ExceptionResult $e){
return Redirect::back()->with('error', $e->getMessage())->withInput();
}
}
post模型
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
//
protected $table = "posts";
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo("AppModelsUser","user_id",'id');
}
public function comments()
{
return $this->hasMany('AppModelsComment','post_id','id')->orderBy("created_at",'desc');
}
}