laravel管理模型插入

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 App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
//

protected $table = "posts";
public $primaryKey = 'id';

public function user()
{
return $this->belongsTo("App\Models\User","user_id",'id');
}

public function comments()
{
return $this->hasMany('App\Models\Comment','post_id','id')->orderBy("created_at",'desc');
}
}
posted @ 2019-10-16 22:45  brady-wang  阅读(577)  评论(0编辑  收藏  举报