DB::table Vs Eloquent Model - Laravel Database Seed
Asked Answered
C

1

5

When researching for Database Seeder, it's common to see people using DB::table('my_table')->insert(['column' => 'value']) in the Seeder classes. I'd like to know the reasoning behind this apparent convention as to why I should use DB::* instead of MyModel::* to perform such tasks.

Citrate answered 15/10, 2015 at 20:14 Comment(1)
I updated my answer with a note about model factories. I prefer the simple seeds because they're fast, but model factories are a good way to use Eloquent when seedingNefen
N
9

Most importantly, because with DB inserts, you can do multiple inserts at once. Especially when seeding many large tables, that's much, much faster than doing one query per insert.

http://laravel.com/docs/master/queries#inserts

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0]
]);

You also don't need to load the Eloquent class or any of the bulk that comes with it. Again, seeding thousands of rows, creating thousands of Eloquent objects... that can take up a lot of memory.

And finally, if there do happen to be bugs or issues with the Eloquent models, your seeds will still work.


There are some downsides. For example if one of your Eloquent models overrides a setter to manipulate and format data before being saved, then you lose that convenience.

And actually, that applies to any model with $timestamps; with DB inserts you'll have to set the created_at and updated_at timestamps manually. But with a seeder, you might want to simulate that items were created days or months or years ago, in which case you wouldn't want those timestamps to be set automatically.


But actually, a lot of people do use model factories. If you do want to use your setters, or automatically assign relationships, and basically take advantage of everything Eloquent offers, then they're great to use for seeding. With the efficiency tradeoffs I mentioned, but sometimes that's worth it.

Nefen answered 15/10, 2015 at 20:41 Comment(1)
This is a good answer, however, according to this other answer it should also be possible to use MyModel::insert(...) to insert many values just like in your example. Wouldn't this suggest that maybe DB::Table() should be deprecated in favor of more simplicity?Holotype

© 2022 - 2024 — McMap. All rights reserved.