首页 > 解决方案 > 调用未定义的方法 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);
    }
}

标签: phplaravelmodel-view-controllercommentsblogs

解决方案


您使用了错误的型号;Blog 模型有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 文档 - Eloquent - 关系 - 多态关系 - 一对多

话虽如此,您的 Comment 模型看起来并不像您想要使用多态关系,因为您专门有一个blog关系方法。如果您没有超过 1 个需要与评论相关的实体,我将不会使用多态关系。


推荐阅读