为什么将重复行存储到 table

Why stored duplicate rows to table

我有自定义查询,用于将已解析的远程帖子添加到 table:

foreach ($parsedPosts as $post) {
    $hasRemotePostAlready = Post::where('remote_post_id', $post->id)->first();
    if(null === $hasRemotePostAlready) {
        $data = [
            'title' => $post->title,
            'description' => $post->description,
            'remote_post_id' => $post->id
        ];
        Post::create($data);
    }
}

变量 $parsedPosts 有超过 3500 个帖子,当我 运行 我的脚本添加帖子时,所有远程帖子都会重复。为什么他们发帖重复,为什么不符合我的条件:

$hasRemotePostAlready = Post::where('remote_post_id', $post->id)->first();

我如何解决重复行问题?

您可以使用 firstOrCreateupdateOrCreate 方法来处理这种情况,请查看 documentation

在你的情况下试试这个:

$hasRemotePostAlready = Post::firstOrCreate(
  [
      'remote_post_id' => $post->id // columns to check if record exists
  ],

  [
      'title' => $post->title,
      'description' => $post->description
  ]
);