php - 调用未定义的方法 App\Models\Comment::comments()
问题描述
我想为我发表的每篇文章添加评论,但我不断收到错误。
评论控制器:
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);
}
}
解决方案
您使用了错误的型号;Blog 模型有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 文档 - Eloquent - 关系 - 多态关系 - 一对多
话虽如此,您的 Comment 模型看起来并不像您想要使用多态关系,因为您专门有一个blog
关系方法。如果您没有超过 1 个需要与评论相关的实体,我将不会使用多态关系。
推荐阅读
- ffmpeg - 为什么通过 HTTP 将图像转换为 ffmpeg 中的视频需要花费大量时间?
- python - 学习率调度器 - PyTorch
- php - 如何使 php $content 中的 html 语法看起来更好?
- django - 删除和恢复文件和级联文件夹 Django
- python - Appy/lambda 将函数应用于其他列中具有特定条件的数据框
- python - 可以使用 tensorflow 函数重写这个嵌套的 for 循环以允许梯度计算吗?
- mips - 用 MIPS 中的另一个字符替换字符串中的特定字符
- cordova - vuejs 和 cordova 不转换默认函数参数
- odoo-12 - 如何在 odoo12 中创建自定义反馈表单以将数据发送到电子邮件?
- sql - 选择列中最常见的所有信息