The querybuilder and eloquent is more or less the same thing. You use the querybuilder to extend your eloquent.
Jun 29, 2021
3
Level 5
DB Query Builder updateOrInsert Vs Eloquent firstOrCreate ( Performance)
I'm using laravel mongodb and trying to import large data from json files. I tried to use Eloquent's firstOrCreate and Query Builder's updateOrInsert. I thought using query builder would be faster but it turned out that it is slower than Eloquent. Can you please help me insert data fast enough because I have millions of data left? The following is my code.
Query Builder
$ids = \Cache::remember('ids', 60 * 60, function () {
return array_merge(...Alert::distinct('facebookId')->get()->toArray());
});
$chunks = array_chunk($this->data,3000);
foreach ($chunks as $posts) {
foreach ($posts as $post) {
if (in_array($post->account->platformId, $Ids)) {
$likeCount = $post->statistics->actual->likeCount;
$commentCount = $post->statistics->actual->commentCount;
DB::collection('posts')->updateOrInsert(
[
'platformId' => $post->platformId
],
[
'url' => $post->postUrl,
'accountId' => $post->account->platformId,
'likes' => $likeCount,
'comments' => $commentCount,
'date' => $post->date ?? ''
]);
}
}
}
Eloquent Builder
$ids = \Cache::remember('ids', 60 * 60, function () {
return array_merge(...Alert::distinct('facebookId')->get()->toArray());
});
$chunks = array_chunk($this->data,3000);
foreach ($chunks as $posts) {
foreach ($posts as $post) {
if (in_array($post->account->platformId, $Ids)) {
$likeCount = $post->likeCount;
$commentCount = $post->commentCount;
Post::firstOrCreate(
[
'platformId' => $post->platformId
],
[
'url' => $post->postUrl,
'accountId' => $post->account->platformId,
'likes' => $likeCount,
'comments' => $commentCount,
'date' => $post->date ?? ''
]);
}
}
}
Please or to participate in this conversation.