php - 调用未定义的方法 App\Models\Comment::comments()

标签 php laravel model-view-controller comments blogs

我想为我发表的每一篇文章添加评论,但我不断收到错误。

评论 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_idcommentable_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/

相关文章:

php - 如何使用 JSON.stringify 在 javascript/node js 中模拟 php 的 json_encode?

php - 对于非常简单的数据,平面文件与 MySQL

php - 后端和前端如何协同工作?

laravel - 在 Laravel View 中使用命名空间

linux - Beanstalkd在系统启动或重启时启动,如何在Centos上取消注释 "START yes"

c# - 如何在 MVC 中忽略查询字符串中的模型绑定(bind)

javascript - 将服务注入(inject) Controller 会引发错误

objective-c - View 了解其 Controller 是否可以?

php - mod 重写,title slugs 和 htaccess

php - 调用函数时出错