Difference between DB::table('table') and

2019-04-07 14:47发布

问题:

on laravel we can access by using DB::table('table')->get(); or using model::('table')->all(); My question is what's the difference between them ?

thanks.

回答1:

You can do this because Model and the DB facade both implement functions that yield a Builder instance.

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html
https://laravel.com/api/5.2/Illuminate/Database/Query/Builder.html

The difference is, instances of Model have properties which set up a Builder with predesignated information, like table, and also provide it with events, relationship information, specific static bindings, and a bunch of other handy helpers that constrain to objects and make object-oriented programming easier.

So yes, you can use a model and then take the query Builder object and change its table (just like you can change anything else about a Builder), but it's fighting a system specifically designed to make query building easier.

At heart, what Laravel does is take the Symfony2 framework and streamline it so everything is simpler. Models are one such instance of this.