Should I use Query Builder for this in Laravel 9?
DB::table('galleries')->insert(
['book_id' => $book->id, 'photo' => $name, 'cover' => 1],
);
or Laravel Eloquent?
Gallery::create(
['book_id' => $book->id, 'photo' => $name, 'cover' => 1],
);
And what is the difference?
CodePudding user response:
They are both basically the same. The only difference comes when you want to insert a huge amount of data.
The performance of query builder is much faster than that of the eloquent ORM when handling VERY LARGE amounts of data.
CodePudding user response:
insert() Query builder method difference:
- the difference is, Query Builder
insert()
runsmysql
raw insert query under the hood and As likemysql
raw query you can create multiple rows in single query.
DB::table('galleries')->insert(
['book_id' => $book->id, 'photo' => <photo A path>, 'cover' => 1],
['book_id' => $book->id, 'photo' => <photo B path>, 'cover' => 0],
);
The above query will insert two rows in single query.
- The second thing is, It is very fast and optimize in speed as compare to eloquent builder
create()
method. - Third, It's not emits
model events
i.e.creating
,created
events etc. - It's not returns created models in result.
create()
eloquent method Difference:
- It's insert only single row at a time. whenever you want insert multiple rows/models then you need to run
create()
method inforeach loop
or needs to usecreateMany()
method.
All of them works same like
create()
. let suppose you want to insert 100 rows in database table then both will runs100 insert
queries under the hood.
It emits model events i.e.
creating
,created
events etc.It returns inserted model in result.
It's slower than
insert()
query builder method because it's handling a lot of computations, events pipelines during insertion.
Suggestion:
If you want to catch model event then must use eloquent()
. If you want query optimization, fast insertion and doesn't have any concern with model events
then user insert()
method.