【发布时间】:2021-10-22 08:19:45
【问题描述】:
我想为我发表的每篇文章添加评论,但我不断收到错误。
评论控制器:
public function store(Request $request)
{
$comments = new Comment;
$comments->body =$request->get('comment_body');
$comments->user()->associate($request->user());
$blogs = Comment::find(1);
$blogs->comments()->save($comments);
return back();
}
评论模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasFactory;
protected $guarded =[];
public function blog()
{
return $this->belongsTo(Blog::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
博客模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
protected $fillable = ['user_id' , 'blog_category_id' , 'title' , 'description'];
public function user()
{
return $this->belongsTo(user::class);
}
public function blogcategory()
{
return $this->hasOne(BlogCategory::class)->withDefault(function($user , $post){
$user->name = "Author";
});
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
【问题讨论】:
-
Welcome to SO ... 为什么要查找评论而不是博客帖子
$blogs = Comment::find(1)? Blog 模型具有comments关系,而不是 Comment 模型 -
但我已经尝试过了。继续重复错误
标签: php laravel model-view-controller comments blogs