首页 > 解决方案 > App\Post::categorys 必须返回一个关系实例,但返回的是“null”。是否使用了“return”关键字?拉拉维尔

问题描述

我不明白为什么它不起作用,这几天一直在做。我正在制作一个显示产品的网站,每个产品都有一个类别,所以我与帖子和类别表建立了关系,但它一直给出这个错误 App\Post::categorys must return a relationship instance, but "null" was returned。是否使用了“return”关键字?

Post.php: (this is the modal section for Post)

public function categorys(){
$this->hasOne(Category::class);
}

Category.php: (this is the modal section for Category)

public function posts(){
$this->hasMany(Post::class);
}

index.blade.php: (index section to display the name of the categories)

{{  $posts->categorys->name }}


***SOLVED*** added return! But now its giving me another problem 
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.post_id' in 'where clause' (SQL: select * from categories where categories.post_id = 1 and categories.post_id is not null limit 1) sorry I am new in Laravel 



 public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->text('description');
            $table->integer('category_id');
            $table->integer('price');
        });
    }



  public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
     });
    }
It keeps giving the error i dont know what seems to be the problem

标签: phplaravel

解决方案


您需要返回关系。喜欢

public function categorys(){
$this->hasOne(Category::class);
}

应该成为

public function categorys(){
return $this->hasOne(Category::class);
}

推荐阅读