尝试在laravel中创建标记系统

时间:2016-06-19 07:19:23

标签: php laravel laravel-5

我正在尝试为自己的用法创建一个标记系统,但我遇到了一些问题

这是我的代码:

 public function postAddPost(Request $request){
    $post = new Post;
    $post->user_id = $request->user_id;
    $post->content = $request->content;
    $post->status = 1;
    $post->save();
    $hashtag_string = $request->tags;
    $postlast=Post::orderby('id','dsc')->first();

    $matches=explode(',',$hashtag_string);
    //looping through matched items in your $matches array
    foreach($matches as $tags)
    {
      $tag = new Tag;
      $tag->post_id = $postlast->id + 1;
      $tag->tagname = $tags;
      $tag->save();
    }
    Session::flash('message','Post added');
    return redirect('/admin/posts');
}

但问题是它给了我这个错误

 SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`test`.`tags`, CONSTRAINT `tags_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)) (SQL: insert into `tags` (`post_id`, `tagname`, `updated_at`, `created_at`) values (0, #hello, 2016-06-19 07:12:37, 2016-06-19 07:12:37))

我知道问题是我正在尝试将标记附加到尚未创建的post_id但是如何在标记创建之前使用post_id创建帖子? 感谢

0 个答案:

没有答案