在多对多关系上,在null上调用成员函数post()

时间:2020-03-11 13:12:40

标签: laravel many-to-many

我创建了两个表来存储帖子信息:

我在其中存储除类别之外的所有信息的帖子表。

每个表的迁移文件如下:

帖子

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('slug');
        $table->longText('excerpt');
        $table->longText('description');
        $table->tinyInteger('feature')->default(1);
        $table->enum('status',['publish','draft']);
        $table->string('image');
        $table->timestamps();
    });

post_categories

Schema::create('post_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('category_id')->nullable();
        $table->unsignedBigInteger('post_id')->nullable();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->foreign('post_id')->references('id')->on('posts');
        $table->timestamps();
    });

现在,我在PostCategory模型中具有以下功能:

public function post(){
  return $this->belongsToMany(Post::class);
}

现在,当我尝试使用以下方法获取数据时:

\App\Models\PostCategory::find(5)->post()->orderBy('created_at')->get();

我在null上调用成员函数post()

我该怎么做才能获得5类职位?

1 个答案:

答案 0 :(得分:2)

您误解了一些概念。

这里您的关系介于帖子类别之间。

发布模型中

public function categories(){
  return $this->belongsToMany(Category::class,'post_categories','post_id','category_id');
}

类别模型

public function posts(){
      return $this->belongsToMany(Post::class,'post_categories','category_id','post_id');
}

现在,您可以自由访问类别中的帖子和帖子中的类别。

$post = Post::with('categories')->where('id',5)->first(); 

这样,您将获得带有其类别的帖子。

$category= Category::with('posts')->where('id',5)->first();

这样,您将获得带有其帖子的类别。

详细了解many to many的工作方式

编辑:-

如果要使用帖子,则要在类别中创建条件。

$post = Post::with('categories')->whereHas('categories', function($q){
    $q->where('id',5);
})->get();