我想为我发表的每一篇文章添加评论,但我不断收到错误。
评论 Controller :
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);
}
}
最佳答案
您使用的型号有误;博客模型具有 comments
关系,而不是 Comment 模型:
$blog = Blog::find(...);
$blog->comments()->save(...);
更新:
您似乎想要使用多态关系,这似乎基于您的 comments
表的结构,因为您有字段 commentable_id
和 commentable_type
。如果您检查多态一对多关系的文档,这与文档中的示例相同:
博客模型:
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
评论模型:
public function commentable()
{
return $this->morphTo();
}
Laravel 8.x Docs - Eloquent - Relationships - Polymorphic Relationships - One to Many
话虽如此,您的 Comment 模型看起来并不像您想要使用多态关系,因为您专门有一个 blog
关系方法。如果您没有超过 1 个需要与 Comment 相关的实体,我将不会使用多态关系。
关于php - 调用未定义的方法 App\Models\Comment::comments(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68867917/