获取 Laravel 中 post 的所有类别

Get all categories of post in Laravel

我创建了一个 table post__post_category_relations 来保存 post 的类别。

Schema::create('post__post_category_relations', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('post_id')->unsinged();
        $table->integer('category_id')->unsinged();
        $table->timestamps();
    });

在 blade 模板编辑 post,我想显示 post 的列表类别。

我在 Post 模型中写道:

public function categories(){
    return $this->belongsTo(PostCategoryRelations::class,'id','post_id','category_id');
}

但它只有return一个类别。你能告诉我如何显示所有类别吗?非常感谢!

这看起来类似于 post 和类别之间的 Many To Many 方法。连接 post 和类别 table 的连接点 table 应该有 post_idcategory_id 并且不需要其他列,例如 idtimestamps() 我猜你不会在你的应用程序中使用它们。 迁移将最小化为

Schema::create('post__post_category_relations', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('post_id')->unsinged();
        $table->integer('category_id')->unsinged();

});

对于多对多,您可以在模型中添加定义,例如

class Post extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class, 'post__post_category_relations', 'post_id');
    }
}


class Category extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class, 'post__post_category_relations', 'category_id');
    }
}

如果您仍想保留其他列与交汇点 table post__post_category_relations,您可以通过在模型中定义为枢轴属性来访问它们,例如

class Post extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class, 'post__post_category_relations', 'post_id')
        ->withPivot('id','cols')
        ->as('post__post_category_relation_cols');
    }
}