Laravel 5.6多对多态关系插入不起作用

时间:2018-09-09 14:40:12

标签: laravel laravel-5.6

我在此项目上使用 laravel 5.6 。未记录“类别值”数据透视表的类别值。我检查了f12或错误,但没有得到任何错误。他们都不错,但没有记录数据透视表。我在哪里 错了。

我的Blog项目sql结构如下

-博客

id 标题 描述 ...

-可分类 category_id categorizable_id categorizable_type

下面的代码属于Category.php模型

class Category extends Model
{
    protected $primaryKey='category_id';

    public function blogs(){
        return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
    }
}

以上代码属于Blog.php

public function category($categories)
    {
        $categories = Blog::buildCatArray($categories);

        foreach ($categories as $catName) {
            $this->addOneCat($catName);
            $this->load('categories');
        }

        return $this;
    }


    public function buildCatArray($categories): array
    {
        if (is_array($categories)) {
            $array = $categories;
        } elseif ($categories instanceof BaseCollection) {
            $array = $this->buildCatArray($categories->all());
        } elseif (is_string($categories)) {
            $array = preg_split(
                '#[' . preg_quote(',;', '#') . ']#',
                $categories,
                null,
                PREG_SPLIT_NO_EMPTY
            );
        } else {

            throw new \ErrorException(
                __CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
                gettype($categories) . ' given'
            );
        }

        return array_filter(
            array_map('trim', $array)
        );
    }



    protected function addOneCat(string $catName)
    {
        $cat = Self::findOrCreate($catName);
        $catKey = $cat->getKey();

        if (!$this->cats->contains($catKey)) {
            $this->categories()->attach($catKey);
        }
    }


    public function find(string $catName)
    {
        return $this->Category::$catName->first();
    }

    public function findOrCreate(string $catName): Category
    {
        $cat = $this->find($catName);

        if (!$cat) {
            $cat = $this->Category::create(['name' => $catName]);
        }

        return $cat;
    }

这是我的Blog Controller文件存储类

BlogController.php

public function store(Request $request)
    {
    $data = new Blog;
    $data->title = $request->title;
    $data->content = $request->content;
    $tags = explode(',',$request->tag);
    $categories = explode(',',$request->category);
    $data->save();
    $data->tag($tags);
    $data->category($categories);
}

最美好的祝愿

0 个答案:

没有答案