首页 > 解决方案 > 使用 corcel 为帖子添加类别

问题描述

我正在使用"jgrossi/corcel": "3.0.0"Laravel 6.16.0并且PHP 7.4.1

我想将现有类别添加Product到我在 wordpress 中的新帖子中。但是,我不知道该怎么做。

我可以通过以下方式创建 wordpress 帖子:

        $post = new Post();
        $post->post_title = $title;
        $post->post_content = $msg;
        $post->save();

有什么建议可以corcel用来将现有类别添加到帖子中吗?

感谢您的回复!

标签: phplaravelcorcel

解决方案


Post 模型与分类模型具有belongsToMany 关系,您可以在此处看到...

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function taxonomies()
{
    return $this->belongsToMany(
        Taxonomy::class,
        'term_relationships',
        'object_id',
        'term_taxonomy_id'
    );
}

//Source: https://github.com/corcel/corcel/blob/5.0/src/Model/Post.php
//Lines: 185-196

因此,您应该能够使用类别 ID 将帖子链接到类别,如下所示...

$post->taxonomies()->associate($taxonomyId);

您可以在此处找到有关这些类型关系的更多信息https://laravel.com/docs/8.x/eloquent-relationships#updating-belongs-to-relationships


推荐阅读