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

为君一笑 提交于 2019-12-06 01:51:21

问题


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.



来源:https://stackoverflow.com/questions/37094902/difference-between-dbtabletable-and-modeltable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!