【问题标题】:Call to undefined method App\Models\Comment::comments()调用未定义的方法 App\Models\Comment::comments()
【发布时间】: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


【解决方案1】:

您使用了错误的型号; 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 Docs - Eloquent - Relationships - Polymorphic Relationships - One to Many

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

【讨论】:

  • 更换型号后出现此错误
  • SQLSTATE[42S22]:未找到列:1054 '字段列表'中的未知列'blog_id'(SQL:插入commentsbodyuser_idblog_id,@ 987654334@, created_at) 值(嘿,?,1,2021-08-20 21:01:45,2021-08-20 21:01:45))
  • 那么您的架构没有按照惯例设置,或者您需要调整关系方法以适应您用来保存博客 ID 的列...您是说 Comment 属于 @ 987654337@ 所以comments 表需要一些字段用于该博客ID
  • 这是我的评论表
  • $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('parent_id')->unsigned(); $table->text('body'); $table->integer('commentable_id')->unsigned(); $table->string('commentable_type'); $table->timestamps(); }); }
猜你喜欢
  • 2022-12-09
  • 2021-04-15
  • 2021-06-21
  • 1970-01-01
  • 2023-02-06
  • 2021-03-19
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多