在laravel 5.2中保存具有多种关系的枢轴

时间:2016-11-02 14:57:05

标签: php laravel

我有下表

User : id, name, email
Article : id, post, created_at
user_article : userid, articleid

表user_article是数据透视表。我可以保存文章表,但是如何保存数据透视表。

这是我在控制器上的代码

public function store(Request $request)
    {
        //
        //dd($request);

        $input = $request->all();
        $article = Article::create($input);
        $article->users()->attach($input);


        return redirect()->back()->with('flash_message', 'Article successfully added!');;

    }

错误说

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`blog`.`user_article`, CONSTRAINT `fk_user_article_articleid` FOREIGN KEY (`articleid`) REFERENCES `article` (`id`) ON DELETE CASCADE)

用户模型:

public function articles() {
        return $this->belongsToMany('App\Article','user_article','userid','articleid');
    }

文章模型:

public function users() {
      return $this->belongsToMany('App\User','user_article','userid','articleid');
    }

有人可以为此提供帮助。谢谢

0 个答案:

没有答案