how to select specific columns in laravel eloquent

2019-03-08 12:48发布

lets say I have 7 columns in table, and I want to select only two of them, something like this

SELECT `name`,`surname` FROM `table` WHERE `id` = '1';

In laravel eloquent model it may looks like this

Table::where('id', 1)->get();

but I guess this expression will select ALL columns where id equals 1, and I want only two columns(name, surname). how to select only two columns?

13条回答
Bombasti
2楼-- · 2019-03-08 13:07

Use following code : -

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();   
查看更多
3楼-- · 2019-03-08 13:13

You can use Table::select ('name', 'surname')->where ('id', 1)->get ().

Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.

查看更多
【Aperson】
4楼-- · 2019-03-08 13:14

You can use get() as well as all()

ModelName::where('a', 1)->get(['column1','column2']);
查看更多
聊天终结者
5楼-- · 2019-03-08 13:18

You first need to create a Model, that represent that Table and then use the below Eloquent way to fetch the data of only 2 fields.

Model::where('id', 1)
         ->pluck('name', 'surname')
         ->all();
查看更多
趁早两清
6楼-- · 2019-03-08 13:24

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();
查看更多
7楼-- · 2019-03-08 13:26
Table::where('id', 1)->get(['name','surname']);
查看更多
登录 后发表回答