0

我有自定义查询将已解析的远程帖子添加到表中:

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();

在我的情况下,如何解决重复行问题?

4

1 回答 1

1

您可以使用这种情况下的firstOrCreateorupdateOrCreate方法,看看文档

在你的情况下试试这个:

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

  [
      'title' => $post->title,
      'description' => $post->description
  ]
);
于 2019-09-15T07:19:46.897 回答