Laravel ManyToMany包含方法问题

时间:2016-11-14 07:08:30

标签: php laravel many-to-many relationship

我在模型文章和关键词之间有很多关系,以避免重复输入我做过(IF)语句测试:

if(!$Article->keywords->contains($keyword1->id)){
                $Article->keywords()->attach($keyword1->id);
           }

事情让我发疯:
1-代码第一次完美运行。
2-在我清空数据库表并再次测试后,它给了我这个错误:

    QueryException in Connection.php line 763:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '34-1' for key 'article_keyword_keyword_id_article_id_unique' (SQL: insert into `article_keyword` (`article_id`, `keyword_id`) values (1, 34))

当我跟踪错误时,即使$Article->keywords()->attach($keyword1->id);给出错误,也会显示执行该行:if(!$Article->keywords->contains($keyword1->id))

以下是完整的代码:

foreach ($ArticleKeywords as $keyword) //ArticleKeywords the keywords table come from the submitted form
        {

           if (keyword::whereTranslation('name', $keyword)->exists())
           {
               $keyword1 = keyword::whereTranslation('name', $keyword)->first();

               if(!$Article->keywords->contains($keyword1->id)){
                    $Article->keywords()->attach($keyword1->id);
               }


            }
            else
            {
                $keyword1 = new Keyword;
                //$data['lang'] was sent from the view to the controller post method
                $keyword1->translateOrNew($data['lang'])->name = $keyword;
                $keyword1->save();
                $user->keywords()->save($keyword1);


                $Article->keywords()->attach($keyword1->id);

            }


        }

0 个答案:

没有答案